我一直在尝试几种方法来删除一些元素,似乎无法让它工作。该计划需要[]
和,
。我试过nums.remove(x)
。
import random
ROWS = 7
COLS = 1
def main():
nums = [0, 0, 0, 0, 0, 0, 0]
for r in range(ROWS):
nums[r] = random.randint(20, 80)
nums = [int(r) for r in nums]
print(nums)
print('The largest integer is',max(nums))
print('The lowest integer is',min(nums))
nums.sort()
print('The middle 5 sorted low to high',nums, )
main()
期望的输出:
79 30 39 33 41 43 53
The highest number is 79
The lowest number is 30
The middle 5 sorted high to low:
43 41 39 33 30
当前输出:
[22, 35, 39, 24, 75, 24, 33]
The largest integer is 75
The lowest integer is 22
The middle 5 sorted low to high [22, 24, 24, 33, 35, 39, 75]
答案 0 :(得分:1)
您可以使用列表解析打印带空格分隔的列表:
print(' '.join([str(x) for x in nums]))
您可以使用切片表示法获取数组的中间5个元素:
print('The middle 5 sorted low to high', ' '.join([str(x) for x in nums[1:-1]))
答案 1 :(得分:0)
你可以,但需要更多时间。打印如下列表:
my_lst = ['0', '0', '0', '0']
print(my_lst)
将产生所需的结果加上括号:
[0, 0, 0, 0]
要删除括号并将数字放在新行中,您可以尝试在新行上分别打印所有数字:
...
print(nums[0], nums[1], nums[2], nums[3], nums[4])
或使用while
循环加上变量:
num = 0
while num < len(nums):
num += 1
print(nums[num])
不幸的是,它最终会在一条线上下降,而不是从左到右。我希望这回答了你的问题!
答案 2 :(得分:0)
也许您可以使用list.pop
删除列表中最大和最低的nums:
import random
ROWS = 7
COLS = 1
def main():
nums = [0, 0, 0, 0, 0, 0, 0]
for r in range(ROWS):
nums[r] = random.randint(20, 80)
nums = [int(r) for r in nums]
largest = max(nums)
lowest = min(nums)
print(nums)
print('The largest integer is',largest)
print('The lowest integer is',lowest)
nums.sort()
nums.pop(0) # remove first
nums.pop(-1) # remove last
print('The middle 5 sorted low to high',nums)
main()
或者用这种方式删除:
import random
ROWS = 7
COLS = 1
def main():
nums = [0, 0, 0, 0, 0, 0, 0]
for r in range(ROWS):
nums[r] = random.randint(20, 80)
nums = [int(r) for r in nums]
largest = max(nums)
lowest = min(nums)
print(nums)
print('The largest integer is',largest)
print('The lowest integer is',lowest)
nums.sort()
nums.remove(largest)
nums.remove(lowest)
print('The middle 5 sorted low to high',nums)
main()
如果列表中有多个最大或最低的nums,请尝试以下函数:
def remove_largest_lowest(alist):
return [i for i in alist if i not in (max(alist),min(alist))]
print remove_largest_lowest([1,1,2,3,1,5,5])
答案 3 :(得分:0)
不适用于积分。
如果您知道正确的库,您可以使您的代码简洁明了。当然,这是矫枉过正,但是,嘿,总是有趣的是有一个替代的答案。在我的回答中,我将使用numpy
生成随机整数。事实证明,这比for
循环要容易得多。
import numpy as np
ROWS = 7
def main():
nums = np.random.randint(20,80,ROWS)
print " ".join([str(n) for n in nums])
print "The largest integer is {}.".format(nums.max())
print "The smallest integer is {}.".format(nums.min())
print "The middle {} sorted low to high are {}.".format(ROWS - 2, ", ".join([str(n) for n in sorted(nums)[1:-1]]))
main()
这样可以运行以下示例:
50 51 78 41 58 37 38
The largest integer is 78.
The smallest integer is 37.
The middle 5 sorted low to high are 38, 41, 50, 51, 58.