首页 > 解决方案 > 如何在下面的代码中使用 for 循环从列表中删除值?

问题描述

b=[2, 3, 0, 5, 0, 7, 0, 0, 0, 11, 0, 13, 0, 0, 0, 17, 0, 19, 0, 0, 0, 23, 0, 0, 0, 0, 0, 29, 0, 31, 0, 0, 0, 0, 0, 37, 0, 0, 0, 41, 0, 43, 0, 0, 0, 47, 0, 0, 0, 0, 0, 53, 0, 0, 0, 0, 0, 59, 0, 61, 0, 0, 0, 0, 0, 67, 0, 0, 0, 71, 0, 73, 0, 0, 0, 0, 0, 79, 0, 0, 0, 83, 0, 0, 0, 0, 0, 89, 0, 0, 0, 0, 0, 0, 0, 97, 0, 0, 0] 
#b is a list of primes with composite numbers turned into zero!
#code to remove zeroes
for k in b:
    if k==0:
        del k
print(b)

我欢迎任何相当简单的建议,因为我是初学者并且是自学成才的。如果有什么我做错了,也请指出。谢谢你

标签: python-3.xfor-loopdel

解决方案


我会使用列表推导来删除所有出现的 0:

b=[2, 3, 0, 5, 0, 7, 0, 0, 0, 11, 0, 13, 0, 0, 0, 17, 0, 19, 0, 0, 0, 23, 0, 0, 0, 0, 0, 29, 0, 31, 0, 0, 0, 0, 0, 37, 0, 0, 0, 41, 0, 43, 0, 0, 0, 47, 0, 0, 0, 0, 0, 53, 0, 0, 0, 0, 0, 59, 0, 61, 0, 0, 0, 0, 0, 67, 0, 0, 0, 71, 0, 73, 0, 0, 0, 0, 0, 79, 0, 0, 0, 83, 0, 0, 0, 0, 0, 89, 0, 0, 0, 0, 0, 0, 0, 97, 0, 0, 0] 
#b is a list of primes with composite numbers turned into zero!
# Iterates through all the values and returns them unless they are 0
b = [x for x in b if not x == 0]
print(b)

推荐阅读