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', '', '']]
>>> 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)
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', '', '')]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With