簡體   English   中英

在Python中合並2d列表和1d列表的最佳方法?

[英]Best way to merge a 2d list and a 1d list in Python?

我需要合並二維列表和單維列表而不會丟失元素。

我使用循環來實現結果,但我想知道是否有更好的方法。

list1 = ["a","b","c","d"]
list2 = [["1","2","3"],["4","5","6"],["7","8"]]
max_column_count = len(list1)
expected_result = [list1]
for row in list2:
    if max_column_count > len(row):
        columns = max_column_count - len(row)
        row += [''] * columns
    expected_result.append(row)
print(expected_result)

產量

[['a', 'b', 'c', 'd'], ['1', '2', '3', ''], ['4', '5', '6', ''], ['7', '8', '', '']]

如果您作為輸出發布的是您的預期輸出,那么使用來自itertools chain將是一種方法:

>>> mx_len = len(max([list1,*list2]))
>>> 
>>> mx_len
4
>>> [x+['']*(mx_len-len(x)) for x in itertools.chain([list1], list2)]
[['a', 'b', 'c', 'd'], ['1', '2', '3', ''], ['4', '5', '6', ''], ['7', '8', '', '']]
>>>
>>> #another way by unpacking list2 in a list with list1
>>>
>>> [x+['']*(mx_len-len(x)) for x in itertools.chain([list1, *list2])]
[['a', 'b', 'c', 'd'], ['1', '2', '3', ''], ['4', '5', '6', ''], ['7', '8', '', '']]

另一種方法是雙拉鏈效果,比如使用zip_longest轉置兩個列表並用''填充缺失值然后再次壓縮列表以恢復原始形狀,這樣:

>>> l1 = itertools.zip_longest(list1, *list2, fillvalue='')
>>> 
>>> l2 = list(zip(*l1))
>>>
>>> l2
[('a', 'b', 'c', 'd'), ('1', '2', '3', ''), ('4', '5', '6', ''), ('7', '8', '', '')]
list1 = ["a","b","c","d"]
list2 = [["1","2","3"],["4","5","6"],["7","8"]]
list3 = []
list3.append(list1)
list3.append(list2)
>>>
list3 =[['a', 'b', 'c', 'd'], [['1', '2', '3'], ['4', '5', '6'], ['7', '8']]]

如果希望結果列表包含相同大小的列表,則填充空字符串:

list1 = ["a","b","c","d"]
list2 = [["1","2","3"],["4","5","6"],["7","8"]]
req_len = len(list1)
result = [list1] + [org + [''*(req_len - len(org))] for org in list2]
print result
>>> list1 = ["a","b","c","d"]
... list2 = [["1","2","3"],["4","5","6"],["7","8"]]
... list3 = [list1] + map(lambda x: x + ['']*(len(list1)-len(x)),list2)
>>> list3
6: [['a', 'b', 'c', 'd'],
 ['1', '2', '3', ''],
 ['4', '5', '6', ''],
 ['7', '8', '', '']]
>>> 

這基本上和你正在做的一樣,但更簡潔。 如果你不了解地圖功能,這是一個學習的好時機( https://docs.python.org/3/library/functions.html#map

暫無
暫無

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

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