【发布时间】:2019-11-25 11:38:33
【问题描述】:
我正在编写一个程序,它给出一个整数列表,识别最小值,然后用列表的次要索引删除最小值。
例如:list = [3, 6, 15, 2, 4, 2] 应该返回 [3, 6, 15, 4, 2] 请注意,由于列表中的次要索引,前 2 个被删除。
这是我的全部代码:
def remove_smallest(numbers):
mylist = []
if not numbers:
return mylist
minimo = min(numbers)
if numbers.count(minimo) > 1:
numbers = numbers[::-1] #My solution to the minor index is to reverse the list and loop. Then reverse again.
#mylist = [item for item in numbers if item != minimo and item not in mylist] #I tried to use a list comprehension, with awful results.
it = iter(numbers)
for item in it:
if item == minimo and item in mylist:
next(it, None)
continue
mylist.append(item)
print(mylist[::-1])
remove_smallest([2, 4, 5, 1, 2, 1])
前两项将附加到“mylist”(1, 2)。 然后,因为 1 在 mylist 上,它会跳过它然后继续。到目前为止一切都很好,但是当它应该选择 5 时,它没有,而是直接进入 4 然后 2,导致在程序末尾看起来像这样的数组: [2, 4, 2, 1 ] 什么时候应该返回 [2, 4, 5, 2, 1]
谢谢
【问题讨论】:
-
删除
next(it, None),它会给出正确的结果。 -
为了澄清 为什么 那就是 -
for item in it:直接推进迭代器,您不需要使用next()手动进行。不相关的建议:numbers.remove(min(numbers))是解决此用例的单线器 -
for循环本身(隐式)调用next。你不需要自己做。 -
谢谢,它也成功了!
标签: python python-3.x list loops iterator