我需要合并二维列表和单维列表而不会丢失元素。
我使用循环来实现结果,但我想知道是否有更好的方法。
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', '', '']]
答案 0 :(得分:5)
如果您作为输出发布的是预期输出,那么使用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', '', '')]
答案 1 :(得分:1)
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']]]
答案 2 :(得分:1)
如果希望结果列表包含相同大小的列表,则填充空字符串:
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
答案 3 :(得分:1)
>>> 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)