按顺序附加到列表列表

时间:2023-01-17 18:15:57

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

有没有办法可以删除冗余列表。谢谢

3 个解决方案

#1


5  

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

使用zip是正确的方法。您只需要添加元组zip产生的元素。

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

#2


1  

You can use zip in a list comprehension:

您可以在列表理解中使用zip:

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)]

#3


1  

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):

作为替代方案,您也可以使用带有sum和lambda函数的map来实现这一点(但是其他答案中提到的列表理解方法更好):

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

#1


5  

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

使用zip是正确的方法。您只需要添加元组zip产生的元素。

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

#2


1  

You can use zip in a list comprehension:

您可以在列表理解中使用zip:

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)]

#3


1  

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):

作为替代方案,您也可以使用带有sum和lambda函数的map来实现这一点(但是其他答案中提到的列表理解方法更好):

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