问题描述
为简单起见,我将仅使用两个列表。 因此,我有以下2D列表:
> > a = [[1,2,3],> > [1,3]]
> > b = [[4,5,6],> > [4,6]]
如果我追加列表a和b,则希望获得以下内容:
masterlist = [[1,4],[2,5],[3,[1,6]]
以下代码是我尝试过的:
filenames = [a,b] #For the example,since I will have multiple arrays
masterlist = []
counter = 0
for file in filenames:
if counter == 0: #This if is to try to create lists within the list
for row in file: #This loops is to iterate throughout the whole list
for col in row:
c = [masterlist.append([col])]
[masterlist.append(c) for row,col in zip(masterlist,c)]
counter = 1
else: #This else is to append each element to their respective position
for row in file:
for col in row:
c = [masterlist.append(col)]
[masterlist.append([c]) for row,c)]
打印主列表时的输出如下:
[[1],[2],[3],[1],[None],4,6,[[None]]]
我不确定[无]的来源。正如我们所看到的,“ 4,6 ...”没有分别附加到列表“ [1],[2],[3] ...”。
解决方法
您可以遍历列表中的项目,然后将其添加到您的主列表中:
a = [[1,2,3],[1,3]]
b = [[4,5,6],[4,6]]
masterlist = []
for aa,bb in zip(a,b): # loop over lists
for itema,itemb in zip(aa,bb): # loop over items in list
masterlist = masterlist + [[itema,itemb]]
输出:
[[1,4],[2,5],[3,6]]
,
如果您使用numpy,这真的很简单
import numpy as np
a = np.array([[1,3]])
b = np.array([[4,6]])
fl = np.vstack(np.dstack((a,b)))
输出
array([[1,6]])