簡體   English   中英

在 python 中的 2D 列表中連接各個 1D 列表的元素

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

我有一個二維列表。 我想合並每個一維列表的第一個元素。 例如。 [[40,0,0],[41,5,10],[3,10,30]]我的 output 列表應如下所示: [[40,0,0,41],[5,10,3,10],[30,0,0,0]]我希望所有元素的長度為 4,方法是從下一個元素中獲取元素,以實現一致的長度 4,當元素結束時,append 歸零以實現長度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)

展平然后以塊的形式迭代(使用石斑魚配方):

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)

Output

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

使其成為一個完整列表, append 剩余零,然后創建四個子列表

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]]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM