简体   繁体   中英

Appending to a list of lists sequentially

I have two list of lists:

my_list = [[1,2,3,4], [5,6,7,8]]
my_list2 = [['a', 'b', 'c'], ['d', 'e', 'f']]

I want my output to look like this:

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

I wrote the following code to do this but I end up getting more lists in my result.

my_list = map(list, (zip(my_list, my_list2)))

this produces the result as:

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

Is there a way that I can remove the redundant lists. Thanks

Using zip is the right approach. You just need to add the elements from the tuples zip produces.

>>> my_list = [[1,2,3,4], [5,6,7,8]]
>>> my_list2 = [['a', 'b', 'c'], ['d', 'e', 'f']]
>>> [x+y for x,y in zip(my_list, my_list2)]
[[1, 2, 3, 4, 'a', 'b', 'c'], [5, 6, 7, 8, 'd', 'e', 'f']]

You can use zip in a list comprehension:

my_list = [[1,2,3,4], [5,6,7,8]]
my_list2 = [['a', 'b', 'c'], ['d', 'e', 'f']]

new_list = [i+b for i, b in zip(my_list, my_list2)]

As an alternative you may also use map with sum and lambda function to achieve this (but list comprehension approach as mentioned in other answer is better):

>>> map(lambda x: sum(x, []), zip(my_list, my_list2))
[[1, 2, 3, 4, 'a', 'b', 'c'], [5, 6, 7, 8, 'd', 'e', 'f']]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM