【问题标题】:How to delete multiple items from a list based on a condition in python如何根据python中的条件从列表中删除多个项目
【发布时间】:2015-08-05 15:41:01
【问题描述】:

我在 python 中有一个这样的列表。

list1=[1,2,4,0,5,0,3,0]

我想从列表中删除所有的 0。我该怎么做呢

【问题讨论】:

标签: python list


【解决方案1】:
list1 = [item for item in list1 if item != 0]

【讨论】:

  • [item for item in list1 if item is not 0] 更加明确
  • @Brobin 但在技术上也是错误的,你不应该假设 python 解释器有一个 [common] 整数的缓存。
  • @TomDalton:由于窥孔优化,它可以在零和一些小整数的情况下工作
  • @inspectorG4dget:但你不能保证 Python 的每个实现和未来版本都会这样。
猜你喜欢
  • 2011-03-17
  • 2015-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-15
相关资源
最近更新 更多