在 python 中的二维列表中加入各个一维列表的元素

Joining elements of respective 1D lists inside 2D list in python

我有一个二维列表。我想合并每个一维列表的第一个元素。 例如。 [[40,0,0],[41,5,10],[3,10,30]] 我的输出列表应该是这样的: [[40,0,0,41],[5,10,3,10],[30,0,0,0]] 我希望所有元素的长度都为 4,方​​法是从下一个元素中获取元素,以实现一致的 4 长度,当元素结束时,追加零以实现 4

的长度

我认为您需要一个新列表,其中每个项目都包含 4 个元素,取自原始列表的链。如果是这种情况,这里有一个解决方案:

l=[[40,0,0],[41,5,10],[3,10,30]]
m=sum(l, [])

res=[m[i:i+4] for i in range(0,len(m), 4)]
res[-1]=res[-1]+[0]*(4-len(res[-1]))

>>> print(res)

[[40, 0, 0, 41], [5, 10, 3, 10], [30, 0, 0, 0]]

根据您的描述,对于任意长度的列表,以下应该有效:

big_list = [[40,0,0],[41,5,10],[3,10,30]]
# Iterates through the sublists (except for the final one)
for index in range(len(big_list)-1):
    # Redefines a sublist to have the the first element of the next, on the end
    big_list[index].append(big_list[index+1][0])
    # Redefines the next sublist to have the first element removed
    big_list[index+1] = big_list[index+1][1:]
print(big_list)

展平然后分块迭代(使用 grouper recipe):

from itertools import zip_longest


def grouper(iterable, n, fillvalue=None):
    """Collect data into fixed-length chunks or blocks"""
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return [list(t) for t in zip_longest(*args, fillvalue=fillvalue)]


lst = [[40,0,0],[41,5,10],[3,10,30]]
flat = [e for l in lst for e in l]

res = grouper(flat, 4, fillvalue=0)
print(res)

输出

[[40, 0, 0, 41], [5, 10, 3, 10], [30, 0, 0, 0]]

使其成为一个完整的列表,附加剩余的零,然后创建四个子列表

l = [[40,0,0],[41,5,10],[3,10,30]]

l = [x for i in l for x in i]

[l.append(0) for x in range(16 - len(l))]

new = [[l[x*count] for x in range(4)] for count in range(1,5)]

print(new)

>>> [[40, 0, 0, 41], [40, 0, 5, 3], [40, 41, 3, 0], [40, 5, 30, 0]]