我是靠谱客的博主 粗暴牛排,这篇文章主要介绍python创建元组_python:从列表创建元组列表,现在分享给大家,希望可以做个参考。

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内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(64)

评论列表共有 0 条评论

立即
投稿
返回
顶部