我正在尝试删除列表中的负值浮点值。包含所有值的原始列表如下所示:
[
0.030079979253112028,
-0.006015995850622406,
-0.08920269709543568,
-25.72356846473029,
-9.770807053941908,
-66.38340248962655,
-188.7778008298755,
-165.95850622406638,
99.99,
33.81404564315352,
0.1742564315352697,
-0.00560109958506224,
-0.008297925311203318,
-1.4044238589211617
]
运行for
循环后显示if num<0: list.remove(num)
列表如下:
[
0.030079979253112028,
-0.08920269709543568,
-9.770807053941908,
-188.7778008298755,
99.99,
33.81404564315352,
0.1742564315352697,
-0.008297925311203318
]
所以一些负面的线索,比如-66.383...
被删除了,但其他人却没有。这是为什么?
答案 0 :(得分:2)
为了说明这里发生的事情以及为什么改变你当前正在迭代的序列是一个坏主意:
1, -1, -1, 0
^ # this is your iterator starting at the beginning
1, -1, -1, 0
^ # after on step we are here your function has deemed this value unworthy
1, _, -1, 0
^ # the value has been removed but we can't have an empty space so everything gets moved forward
1, -1, 0
^ # now everything has shifted forward but our iterator has not moved.
1, -1, 0
^ # Our iterator goes to the next step without ever having evaluated the value that got shifted in to the removed values place.
您会注意到您的模式结果是列表中剩余的底片始终以另一个负片开头。最好的做法是创建一个新的列表,列出您不需要的值或对象:
new_list = [x for x in old_list if foo(x)]
答案 1 :(得分:0)
您正在迭代并改变列表,这意味着您最终删除了错误的元素,您可以使用reversed:
for num in reversed(lst):
if num < 0:
lst.remove(num)
或制作副本:
for num in lst[:]:
if num < 0:
lst.remove(num)
您还可以使用list comp修改原始列表:
lst[:] = [num for num in lst if num >= 0]