我面临着相当奇怪的列表情况。在这种情况下,Python 似乎对删除哪些零非常有选择性:count = 0a = ["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 += 1print(a, count)仅删除 10 个零中的 6 个。为什么 ?
3 回答
芜湖不芜
TA贡献1796条经验 获得超7个赞
一个更好的解决方案是只创建一个不包含 0 的新列表:
b = [x for x in a if x != 0]
count = len(a) - len(b)
HUX布斯
TA贡献1876条经验 获得超6个赞
要解决评论中的人描述的问题,您可以执行以下操作:
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
largeQ
TA贡献2039条经验 获得超7个赞
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]
添加回答
举报
0/150
提交
取消