python - 删除后列表中仍为零(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!
解决方案
只需这样做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)
推荐阅读
- css - 在 CSS 变换缩放过渡结束时跳转
- javascript - 如何在 Robot Framework 中使用 javascript 获取元素的值?
- api - FMC API POST 请求不起作用。"description": '无效请求
- c++ - C++ 捕获可变参数模板参数中所有指针包装器的值
- reactjs - 使用反应状态附加到对象
- python - 仅过滤具有熊猫条件的组中的一行
- selenium - AttributeError 问题:'WebDriver' 对象没有属性'page'
- python - Ubuntu Virtualbox:重启后 PYTHONPATH 消失了
- javascript - 如何使用对象制作可以根据您的回复发送消息的聊天机器人?
- visual-studio-code - VSCode - 格式化 - 每当我关闭标签时,它都会跳到最左边。怎么修?