list.remove()不会删除所有实例

时间:2019-10-04 13:41:04

标签: python python-3.x list

我面对清单上的异常情况。在这种情况下,Python似乎对删除哪些零非常有选择性:

count = 0
a = ["a",0,0,"b",None,"c","d",0,1,False,0,1,0,3,[],0,1,9,0,0,{},0,0,9]

for x in a:
    if x == 0:
        a.remove(x)
        count += 1

print(a, count)

10个零中只有6个被删除。为什么?

3 个答案:

答案 0 :(得分:3)

更好的解决方案是只创建一个不包含0的新列表:

b = [x for x in a if x != 0]
count = len(a) - len(b)

答案 1 :(得分:0)

要解决这些人在评论中描述的问题,您可以执行以下操作:

count = 0
a = ["a",0,0,"b",None,"c","d",0,1,False,0,1,0,3,[],0,1,9,0,0,{},0,0,9]
for x in a.copy():
    if x == 0:
        a.remove(x)
        count += 1
print(a, count)

然后,您将遍历原始的a,同时在遇到原始0时将其减少>>> False == 0 True

注意事项:

Vue.mixin({
  methods: {
    $propagatedEmit: function (event, payload) {
      let vm = this.$parent;
      while (vm) {
        vm.$emit(event, payload);
        vm = vm.$parent;
      }
    }
  }
})

答案 2 :(得分:0)

x = ["a",0,0,"b",None,"c","d",0,1,False,0,1,0,3,[],0,1,9,0,0,{},0,0,9]

list(filter(lambda a: a != 0, x))

输出

['a', 'b', None, 'c', 'd', 1, 1, 3, [], 1, 9, {}, 9]