Python:将多个2D列表附加到一个2D列表
为了简单起见,我将只使用两个列表。 因此,我有以下2D列表:Python:将多个2D列表附加到一个2D列表,python,list,loops,2d,Python,List,Loops,2d,为了简单起见,我将只使用两个列表。 因此,我有以下2D列表: > > a = [[1,2,3], > > [1,2,3]] > > b = [[4,5,6], > > [4,5,6]] 如果我附加列表a和b,我希望得到以下结果: masterlist = [[1,4], [2,5], [3,6], [1,4], [2,5], [3,6]] [[1], [2], [3], [1], [2], [3], [None], 4
> > a = [[1,2,3],
> > [1,2,3]]
> > b = [[4,5,6],
> > [4,5,6]]
如果我附加列表a和b,我希望得到以下结果:
masterlist = [[1,4], [2,5], [3,6], [1,4], [2,5], [3,6]]
[[1], [2], [3], [1], [2], [3], [None], 4, 5, 6, 4, 5, 6, [[None]]]
以下代码是我尝试过的:
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, col in zip(masterlist, c)]
打印主列表时的输出如下所示:
masterlist = [[1,4], [2,5], [3,6], [1,4], [2,5], [3,6]]
[[1], [2], [3], [1], [2], [3], [None], 4, 5, 6, 4, 5, 6, [[None]]]
我也不确定[没有]是从哪里来的。如我们所见,“4,5,6…”并没有分别添加到列表“[1]、[2]、[3]…”中。您可以遍历列表中的项目,然后将它们添加到主列表中:
a = [[1,2,3],
[1,2,3]]
b = [[4,5,6],
[4,5,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], [1, 4], [2, 5], [3, 6]]
如果你使用numpy,这真的很容易
import numpy as np
a = np.array([[1,2,3],
[1,2,3]])
b = np.array([[4,5,6],
[4,5,6]])
fl = np.vstack(np.dstack((a,b)))
输出
array([[1, 4],
[2, 5],
[3, 6],
[1, 4],
[2, 5],
[3, 6]])