首页 > 解决方案 > 将 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] 只?

提前致谢。

标签: pythonlistfor-loop

解决方案


由于您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,因为它是一个数字比较。


推荐阅读