合并两个列表以制作列表列表

时间:2014-04-27 18:26:10

标签: python arrays list

我想合并两个列表:

a = [1,2,3,4,"a"]
b = [1,2,3,4,"b"]

制作:

[[1,1], [2,2], [3,3], [4,4], ["a","b"]]

这样做的最佳方式是什么?

如果可能的话,我还想附加更多名单,如下:

c = [5,6,7,8,"c"]

获取

[[1,1,5], [2,2,6], [3,3,7], [4,4,8], [5,5,9], ["a","b","c"]

您可以假设列表的长度相同。

1 个答案:

答案 0 :(得分:4)

您可以使用ziplist comprehension

>>> a = [1, 2, 3, 4, "a"]
>>> b = [1, 2, 3, 4, "b"]
>>> new_lst = [list(x) for x in zip(a, b)]
>>> new_lst
[[1, 1], [2, 2], [3, 3], [4, 4], ['a', 'b']]
>>>

修改

关于您更新的问题,如果您以后想要添加另一个列表,可以使用:

>>> c = [5, 6, 7, 8, "c"]
>>> [x + [y] for x,y in zip(new_lst, c)]
[[1, 1, 5], [2, 2, 6], [3, 3, 7], [4, 4, 8], ['a', 'b', 'c']]
>>>

当然,如果您要开始使用所有三个列表,那么您需要做的就是给zip另一个参数:

>>> a = [1, 2, 3, 4, "a"]
>>> b = [1, 2, 3, 4, "b"]
>>> c = [5, 6, 7, 8, "c"]
>>> new_lst = [list(x) for x in zip(a, b, c)]
>>> new_lst
[[1, 1, 5], [2, 2, 6], [3, 3, 7], [4, 4, 8], ['a', 'b', 'c']]
>>>