Best way to combine 2d list and 1d list in Python?

I need to combine a two-dimensional list and a one-dimensional list without losing elements.

I used a loop to achieve the result, but I would like to know if there is a better way.

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)

Exit

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

If what you post as output is your expected result, then using chainfrom itertoolswill be one of the ways:

>>> 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 '', zip , , :

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

, , :

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

This is essentially the same as you, but more concise. If you don't know about the map function, this is a good time to learn ( https://docs.python.org/3/library/functions.html#map )

+1
source
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']]]
0
source

Source: https://habr.com/ru/post/1627293/


All Articles