也许我过度思考它但我无法想出以我需要的方式组合列表的方法
[1,2,3,4,5]
['A','E','I','I','U']
导致
[[1,'A'],[2,'E'],[3,'I'],[4,'O'],[5,'U']]
如果我将它们组合在一起,我会得到元组/圆括号
答案 0 :(得分:4)
您可以使用zip
。
如果你想要内部列表而不是内部元组,也可以使用map
。
map(list, zip(list_1, list_2))
这会将list
函数应用于压缩列表中的每个元组,并为您提供列表列表。
(问题指定Python 2.7,但在Python 3中,map
不返回列表,因此您还必须将list
函数应用于映射的结果;即{{ 1}})
答案 1 :(得分:3)
如果您确实需要列表清单,则必须执行以下操作:
>>> a = [1, 2, 3, 4, 5]
>>> b = ['a', 'b', 'c', 'd', 'e']
>>> result = [list(zipped) for zipped in zip(a, b)]
>>> result
[[1, 'a'], [2, 'b'], [3, 'c'], [4, 'd'], [5, 'e']]
答案 2 :(得分:0)
这是zip
的用途
list_a = [1,2,3,4,5]
list_b = ['A','E','I','I','U']
list_res = zip(list_a, list_b) # Python 2.7
list_res = list(zip(list_a, list_b)) # Python 3 onward
如果你确实希望内部容器是元组,那么你可以使用map
作为@khelwood提议或列表理解,或显式循环,或者......
list_of_lists = map(list, list_res) # Python 2.7
list_of_lists = list(map(list, list_res)) # Python 3 onward
请注意map
和zip
在两个Python版本上的类似行为。在python 2上,他们返回了列表,而在Python 3上,他们返回了迭代器。