首页 > 解决方案 > 删除后列表中仍为零(Python)

问题描述

我在Prob下方有一个列表,当我尝试删除 0 或删除 0.0 时,它有时不会从列表中删除,或者列表中仍有 0 的“另一个版本”。我如何确保从列表中删除所有零“风味”,因为不可能列出所有可能的零小数增量?

 x = [0.0,
 0.0,
 0,
 0.0009765625,
 0.0003255208333333333,
 0.0021158854166666665,
 0.005045572916666667,
 0.013020833333333334,
 0.019856770833333332,
 0.0107421875,
 0.004557291666666667,
 0.000]
    
if 0 in probability_perpoint:
    probability_perpoint.remove(0)
if 0.0 in probability_perpoint:
    probability_perpoint.remove(0.0)

`print(x)` # still prints 0's!

标签: pythonlist

解决方案


只需这样做list comprehension

x = [0.0,0.0,0,0.0009765625,0.0003255208333333333,0.0021158854166666665,0.005045572916666667,0.013020833333333334,0.019856770833333332,0.0107421875,0.004557291666666667,0.000]
x = [i for i in x if i != 0]
print(x)

演示: https ://rextester.com/NAVN53491

remove()和的另一种方式while

x = [0.0,0.0,0,0.0009765625,0.0003255208333333333,0.0021158854166666665,0.005045572916666667,0.013020833333333334,0.019856770833333332,0.0107421875,0.004557291666666667,0.000]
try:
    while True:
        x.remove(0)
except ValueError:
    pass
 
print(x)

演示: https ://rextester.com/YTXM11780


推荐阅读