浮动不评价为负面(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
]
当我为循环运行循环时,如果
如果num <0:list.remove
[
0.030079979253112028,
-0.08920269709543568,
-9.770807053941908,
-188.7778008298755,
99.99,
33.81404564315352,
0.1742564315352697,
-0.008297925311203318
]
所以一些负面的线索,如 -66.383 ...
被删除,但其他人没有。为什么会这样呢?
您正在遍历并更改列表,这意味着您最终删除了错误的元素,您可以使用倒转:
为倒数(lst)中的数字:
if num< 0:
lst.remove(num)
或者复制:
对于lst [:]中的数字:
if num< 0:
lst.remove(num)
您也可以使用list comp来修改原始列表:
lst [:] = [num for lst if num> = 0]
I am trying to delete floating point values in a list that are negative. The original list with all of the values looks like this:
[
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
]
After I run a for
loop that says if num<0: list.remove(num)
the list looks like this:
[
0.030079979253112028,
-0.08920269709543568,
-9.770807053941908,
-188.7778008298755,
99.99,
33.81404564315352,
0.1742564315352697,
-0.008297925311203318
]
So some of the negative vlues, like -66.383...
got deleted, but others didn't. Why is this?
You are iterating over and mutating the list which means you end up removing the wrong elements, you can use reversed:
for num in reversed(lst):
if num < 0:
lst.remove(num)
Or make a copy:
for num in lst[:]:
if num < 0:
lst.remove(num)
You can also use a list comp to modify the original list:
lst[:] = [num for num in lst if num >= 0]
这篇关于浮动不评价为负面(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!