python - 将 for 循环转换为 List
问题描述
我正在研究这个程序:
for n in range (0,31):
if n%2 is 0:
if (n%2)is 0 and (n%5)is 0:
print(n)
我希望输出是这样的,在列表中。
[0,10,20,30]
我试图添加 list.append,
hehe = []
for n in range (0,31):
if n%2 is 0:
if (n%2)is 0 and (n%5)is 0:
hehe.append(n)
print(hehe)
但结果是这样的。
[0]
[0, 10]
[0, 10, 20]
[0, 10, 20, 30]
我如何使它成为 [0,10,20,30] 只?
提前致谢。
解决方案
由于您print
在循环内,因此每次迭代都会将其打印出来。您想将 print 语句移到末尾。此外,您的第一个if
语句是多余的,因为您在第二个语句中再次进行相同的检查,因此您可以将其删除:
hehe = []
for n in range(0,31):
if (n%2)==0 and (n%5)==0:
hehe.append(n)
print(hehe)
最后,这种循环是列表理解的理想候选者:
hehe = [n for n in range(0, 31) if (n%2)==0 and (n%5)==0]
print(hehe)
另请注意,您应该0
使用==
而不是检查值is
,因为它是一个数字比较。
推荐阅读
- python-3.x - 这个端点(flask+sqlalchemy+sqlite)是否会成为大量数据的瓶颈?
- three.js - 如何在 Autodesk forge 查看器 setTheming 颜色方法中使用十六进制颜色代码?
- c++ - 提供对不同类型数据的线程安全访问的类(提案、代码审查)
- javascript - 为什么将导航栏链接包装在容器中会破坏此布局?
- c# - 为什么 LINQ 在我的查询中使用错误的数据类型,而它在 EF 架构中被正确声明?
- flutter-web - 引发了另一个异常:执行平台检查时出现“ErrorSummary”实例 Flutter web
- css - 在 React Native SectionList 上应用样式
- docker - 如何生成自定义 Docker 内容信任根密钥
- php - 使用 AJAX 请求 PHP 文件数据
- python-3.x - 断开 tweepy 流