python-3.x - 如何在下面的代码中使用 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)
我欢迎任何相当简单的建议,因为我是初学者并且是自学成才的。如果有什么我做错了,也请指出。谢谢你
解决方案
我会使用列表推导来删除所有出现的 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)
推荐阅读
- .net - 在 system.array 上调用 replace 方法
- javascript - 异步数据加载后的jQuery执行函数
- c# - 为什么 ConversationReference 服务 url 与 localhost 不同?
- c# - NReco HtmlToPdfConverter 错误:指定的可执行文件不是此 OS 平台的有效应用程序
- c# - 刚体不粘在盒子上
- javascript - Drop-downs are not showing in my HTML table while calling ajax or putting static JSON
- r - 有条件地组合数据框中不同列中的单词
- vim - Vim:使用 v:count1 作为映射的参数
- java - 在 for 循环中循环 else 语句?
- ios - 表视图不刷新