问题描述
给定二维列表
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,e3,b4,d6,a7,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 个或多个内部列表)
解决方法
我会这样做:
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,runnio9ng:
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']
,
itertools 中还有一个有用的函数:
from itertools import zip_longest
zipped = list(zip_longest(*twoDList))
这为您提供了以下布局:
[('a1','e1'),('a2','e2'),('a3','e3'),('a4',None),('a5',None,('a6',('a7',(None,'c9',None)]
然后将它们粘在一起而忽略无
result = [x for y in zipped for x in y if x is not None]