概述
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...
解决方案
Use the builtin function zip():
In Python 3:
z = list(zip(x,y))
In Python 2:
z = zip(x,y)
最后
以上就是粗暴牛排为你收集整理的python创建元组_python:从列表创建元组列表的全部内容,希望文章能够帮你解决python创建元组_python:从列表创建元组列表所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复