Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

merge

list

I need to merge a two dimensional list and a single dimensional list without losing elements.

I used a loop to achieve the result but I'd 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)

output

[['a', 'b', 'c', 'd'], ['1', '2', '3', ''], ['4', '5', '6', ''], ['7', '8', '', '']]
like image 788
Sinan Çetinkaya Avatar asked Mar 14 '23 09:03

Sinan Çetinkaya


2 Answers

>>> 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 what you're doing, but more terse. 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)

like image 32
greg_data Avatar answered Mar 23 '23 13:03

greg_data


If what you post as output is your expected output, then using chain from itertools will be one way to go:

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

Another way would be a double zipping effect, like transposing both lists using zip_longest and fill the missing values with '' then zipping again the lists to get back to the original shape, this way:

>>> l1 = itertools.zip_longest(list1, *list2, fillvalue='')
>>> 
>>> l2 = list(zip(*l1))
>>>
>>> l2
[('a', 'b', 'c', 'd'), ('1', '2', '3', ''), ('4', '5', '6', ''), ('7', '8', '', '')]
like image 106
Iron Fist Avatar answered Mar 23 '23 14:03

Iron Fist