I have two lists:
我有两个清单:
x = ['1', '2', '3']
y = ['a', 'b', 'c']
and I need to create a list of tuples from these lists, as follows:
我需要从这些列表中创建一个元组列表,如下所示:
z = [('1','a'), ('2','b'), ('3','c')]
I tried doing it like this:
我尝试这样做:
z = [ (a,b) for a in x for b in y ]
but resulted in:
但结果是:
[('1', '1'), ('1', '2'), ('1', '3'), ('2', '1'), ('2', '2'), ('2', '3'), ('3', '1'), ('3', '2'), ('3', '3')]
i.e. a list of tuples of every element in x with every element in y... what is the right approach to do what I wanted to do? thank you...
即x中每个元素的元组列表,y中的每个元素......做我想做的事情的正确方法是什么?谢谢...
EDIT: The other two duplicates mentioned before the edit is my fault, indented it in another for-loop by mistake...
编辑:在编辑之前提到的另外两个重复是我的错误,错误地将它缩进到另一个for循环中...
3 个解决方案
#1
43
Use the builtin function zip()
:
使用内置函数zip():
In Python 3:
在Python 3中:
z = list(zip(x,y))
In Python 2:
在Python 2中:
z = zip(x,y)
#2
11
You're looking for the zip builtin function. From the docs:
您正在寻找zip内置功能。来自文档:
>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> zipped
[(1, 4), (2, 5), (3, 6)]
#3
8
You're after the zip function.
你是在拉链功能之后。
Taken directly from the question: How to merge lists into a list of tuples in Python?
直接来自问题:如何将列表合并到Python中的元组列表中?
>>> list_a = [1, 2, 3, 4]
>>> list_b = [5, 6, 7, 8]
>>> zip(list_a,list_b)
[(1, 5), (2, 6), (3, 7), (4, 8)]
#1
43
Use the builtin function zip()
:
使用内置函数zip():
In Python 3:
在Python 3中:
z = list(zip(x,y))
In Python 2:
在Python 2中:
z = zip(x,y)
#2
11
You're looking for the zip builtin function. From the docs:
您正在寻找zip内置功能。来自文档:
>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> zipped
[(1, 4), (2, 5), (3, 6)]
#3
8
You're after the zip function.
你是在拉链功能之后。
Taken directly from the question: How to merge lists into a list of tuples in Python?
直接来自问题:如何将列表合并到Python中的元组列表中?
>>> list_a = [1, 2, 3, 4]
>>> list_b = [5, 6, 7, 8]
>>> zip(list_a,list_b)
[(1, 5), (2, 6), (3, 7), (4, 8)]