作为Python(SAGE)的初学者,我想把这个for循环的输出 进入列表:
for y in [0,8] :
for z in [0,1,2,3] :
x=y+z
print x
输出为
0
1
2
3
8
9
10
11
(垂直)。我想要一个列表,以便我可以将其用于以后的操作: 我想要 [1,2,3,8,9,10,11]。 我发现了一个类似的问题,我意识到输出被重新计算 每一次。有没有一种简单的方法将它们存储在列表中?根据其他答案的建议,我尝试像这样“追加”,但它给出了错误消息:
x=[]
for y in [0,2*3] :
for z in [0,1,2,3] :
x=y+z
x.append(x)
print x
最佳答案
你有很多方法!首先,作为原始代码,您可以执行以下操作:
lst=[]
for y in [0,8] :
for z in [0,1,2,3] :
x=y+z
lst.append(x)
print lst
您可以尝试列表理解
:
lst = [y+z for y in [0,8] for z in [0,1,2,3]]
print lst
您还可以使用itertool链
:
import itertools
lst = list(itertools.chain(*[range(i, i+4) for i in [0,8]]))
print lst
另一种方法是itertool产品
:
import itertools
lst = [y+z for y,z in list(itertools.product([0,8], [0,1,2,3]))]
print lst
在所有情况下,输出
均为:[0, 1, 2, 3, 8, 9, 10, 11]
关于python - 如何将Python循环输出放入列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39322625/