不计算为负的浮点(Python)

2024-06-03 03:47:00 发布

您现在位置: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...被删除了,但是其他的没有。为什么呢?你知道吗


Tags: 语言列表forifnumremovelist浮点
2条回答

如果您对列表进行迭代和变异,这意味着您最终删除了错误的元素,您可以使用reversed

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

或复制:

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

也可以使用列表组件修改原始列表:

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

相关问题 更多 >