Python:将2个有序列表组合成元组列表 [英] python: combine 2 ordered lists into list of tuples
本文介绍了Python:将2个有序列表组合成元组列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有2个列表,我想合并为一个元组列表,以便保持顺序,并且result[i]
是(first[i], second[i])
.假设两个列表的大小始终相同.有没有一种方法可以使用列表推导?例如:
I have 2 lists that I want to combine into a single list of tuples, so that order is maintained and the result[i]
is (first[i], second[i])
. Assume that the two lists will always be of the same size. Is there a way to do this using list comprehension? So for example:
>>> first = [1,2,3]
>>> second = [4,5,6]
>>> combine(first, second)
[(1,4), (2,5), (3,6)]
我尝试了一些事情
[(i,j) for i in first, j in second]
[(i for i in first, j for j in second)]
[(i,j) for i,j in first, second]
这些都不起作用.我只是想知道这是否可行,或者是否必须使用循环来实现.
None of these work. I'm just wondering if this is possible or if I have to do it using a loop.
推荐答案
使用邮政编码:
list(zip(first, second))
Out[384]: [(1, 4), (2, 5), (3, 6)]
这篇关于Python:将2个有序列表组合成元组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文