浮点数未评估为负数 (Python)

Floats not evaluating as negative (Python)

我正在尝试删除列表中的负数浮点值。包含所有值的原始列表如下所示:

[
    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... 被删除了,但其他人没有。这是为什么?

您正在迭代和改变列表,这意味着您最终删除了错误的元素,您可以使用 reversed:

for num in reversed(lst):
    if num < 0:
        lst.remove(num)

或复制:

for num in lst[:]:
    if num < 0:
        lst.remove(num)

您也可以使用列表comp修改原始列表:

lst[:] = [num for num in lst if num >= 0]

举例说明此处发生的情况以及为什么改变当前正在迭代的序列是个坏主意:

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)]