如何迭代2d列表和每个内部列表的备选项?



给定二维列表

twoDList = [[a1,a2,a3,a4,a5,a6,a7],[b1,b2,b3,b4],[c1,c2,c3,c4,c5,c6,c7,c8,c9],[d1,d2,d3,d4,d5,d6],[e1,e2,e3]]

我如何迭代这个二维数组?

answer = alternate(twoDList)
print(answer)
'[a1,b1,c1,d1,e1,a2,b2,c2,d2,e2,a3,b3,c3,d3,e3,a4,b4,c4,d4,a5,c5,d5,a6,c6,d6,a7,c7,c8,c9]'

我试过用这个代码:

def alternateShoes(twodShoes):
numOfBrands = len(twodShoes)
brandCount = 0
shoecount = 0
masterList = []
if numOfBrands != 0:
for shoes in itertools.cycle(twodShoes):
if (brandCount == numOfBrands):
masterList.append(shoes[shoecount])
brandCount = 0
shoecount = shoecount + 1
else:
masterList.append(shoes[shoecount])
brandCount = brandCount + 1
return masterList

但是我卡住了,因为每个内部列表可以有不同的长度。注意,可以有任意数量的内部列表。(0个或多个内部列表)

在itertools中还有一个有用的函数:

from itertools import zip_longest
zipped = list(zip_longest(*twoDList))

这给了你一个布局:

[('a1', 'b1', 'c1', 'd1', 'e1'),
('a2', 'b2', 'c2', 'd2', 'e2'),
('a3', 'b3', 'c3', 'd3', 'e3'),
('a4', 'b4', 'c4', 'd4', None),
('a5', None, 'c5', 'd5', None),
('a6', None, 'c6', 'd6', None),
('a7', None, 'c7', None, None),
(None, None, 'c8', None, None),
(None, None, 'c9', None, None)]

那么就把它们放在一起忽略none

result = [x for y in zipped for x in y if x is not None]

我是这样做的:

def mergeLists(inlst):
rslt = []
lstlens = []
for l in inlst:
lstlens.append(len(l))
mxlen = max(lstlens)
for i in range(mxlen):
for k in range(len(inlst)):
if i < lstlens[k]:
rslt.append(inlst[k][i])
return rslt  

因此,给定在您的问题中定义的输入twoDList,运行:

print(mergeLists(twoDList))

收益率:

['a1', 'b1', 'c1', 'd1', 'e1', 'a2', 'b2', 'c2', 'd2', 'e2', 'a3', 'b3', 'c3', 'd3', 'e3', 'a4', 'b4', 'c4', 'd4', 'a5', 'c5', 'd5', 'a6', 'c6', 'd6', 'a7', 'c7', 'c8', 'c9']