python:从列表创建元组列表
我有两个列表:
x = ['1', '2', '3']
y = ['a', 'b', 'c']
我需要从这些列表创建一个元组列表,如下所示:
z = [('1','a'), ('2','b'), ('3','c')]
我尝试这样做:
z = [ (a,b) for a in x for b in y ]
但结果是:
[('1', '1'), ('1', '2'), ('1', '3'), ('2', '1'), ('2', '2'), ('2', '3'), ('3', '1'), ('3', '2'), ('3', '3')]
即 x 中每个元素与 y 中每个元素的元组列表...做我想做的事情的正确方法是什么?谢谢...
编辑:编辑之前提到的另外两个重复项是我的错,错误地在另一个 for 循环中缩进了它...
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...
EDIT: The other two duplicates mentioned before the edit is my fault, indented it in another for-loop by mistake...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用内置函数
zip()
:在 Python 中3:
在Python 2中:
Use the builtin function
zip()
:In Python 3:
In Python 2:
您正在寻找 zip 内置 函数。
来自文档:
You're looking for the zip builtin function.
From the docs:
您正在寻找 zip 功能。
直接取自问题:如何合并列表Python 中的元组列表?
You're after the zip function.
Taken directly from the question: How to merge lists into a list of tuples in Python?