如何遍历 2d 列表并用每个内部列表替换项目?

How to iterate through 2d list and alternate items with each inner list?

给定二维列表

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 个或更多内部列表)

我会这样做:

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,运行 nio9ng:

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', '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)]

那么就把它们粘在一起,忽略 Nones

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