我有一个数字列表 [5, 3, 1, 6],我想在 python 中进行迭代,用列表中的最小值减去列表中的每个数字,所以结果将是: 第一次迭代会减去 1 作为最小的,所以结果将是 [5,3,null,6],第二次迭代的结果将是 [2,null,null,3] 并且直到给出为止不会停止最终结果为 [null,null,null,1]
我尝试了这段代码,但不知何故它无法使“null”:
def subtract_smallest(lst):
while True:
smallest = min(lst)
if smallest == float('inf'): # All elements are subtracted to the minimum possible extent
break
lst = [x - smallest for x in lst if x > smallest]
print(lst)
numbers = [5,3,1,6]
subtract_smallest(numbers)
这是结果:
[4, 2, 5]
[2, 3]
[1]
[]
当我尝试用 print('null') 更改 'break' 时,它给了我一个错误
def subtract_smallest(lst):
while True:
smallest = min(lst)
if smallest == float('inf'): # All elements are subtracted to the minimum possible extent
print('null')
lst = [x - smallest for x in lst if x > smallest]
print(lst)
numbers = [5,3,1,6]
subtract_smallest(numbers)
当号码列表为空时,您需要停止循环,因为您无法在空列表上调用
min()
。
如果您用字符串替换最小元素
null
,则在获取最小值和减法时必须跳过它。
def subtract_smallest(lst):
while True:
nums = [x for x in lst if x != 'null']
if len(nums) == 1:
break
smallest = min(nums)
lst = [x - smallest if x != 'null' and x > smallest else 'null' for x in lst]
print(lst)
Error message:
ValueError Traceback (most recent call last)
Cell In[6], line 11
8 print(lst)
10 numbers = [5,3,1,6]
---> 11 subtract_smallest(numbers)
Cell In[6], line 3, in subtract_smallest(lst)
1 def subtract_smallest(lst):
2 while True:
----> 3 smallest = min(lst)
4 if smallest == float('inf'): # All elements are subtracted to the minimum possible extent
5 print('null')
ValueError: min() arg is an empty sequence