每次进入for
循环时,我想以某种方式附加到新列表。目前我有:
A=[ ]
B = [ ]
C = [ ]
For i in range (1, 4):
if i == 1:
A.append(x)
if i == 2:
B.append(x)
...
等等。我正在寻找一种更简单的方法,因为它感觉很难编码。
答案 0 :(得分:1)
您可以简单地使用列表列表:
>>> A=[ ]
>>> B = [ ]
>>> C = [ ]
>>> allLists =[A,B,C]
>>> X=range(10,20)
>>> for i,j in enumerate(X):
... allLists[i%len(allLists)].append(j)
...
>>> A,B,C
([10, 13, 16, 19], [11, 14, 17], [12, 15, 18])
另一种方法是使用切片:
>>> def chunk(l,n):
... result=[]
... for i in range(n):
... result.append(l[i::n])
... return result
...
>>> A,B,C=chunk(X,3)
>>> A,B,C
([10, 13, 16, 19], [11, 14, 17], [12, 15, 18])
>>> A,B,C,D=chunk(X,4)
>>> A,B,C,D
([10, 14, 18], [11, 15, 19], [12, 16], [13, 17])