如何将2元组的列表分成两个列表? [英] How to split a list of 2-tuples into two lists?

查看:398
本文介绍了如何将2元组的列表分成两个列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多2元组的列表. 我想将列表分为两个列表,一个列表由列表中所有元组的第一个元素组成,另一个列表由所有元组的第二个元素组成.我想知道如何有效地做到这一点?谢谢!

I have a list of many 2-tuples. I would like to split the list into two lists, one list consisting of the first elements of all the tuples in the list, and the other list consisting of the second elements of all the tuples. I wonder how to do that efficiently? Thanks!

例如,我有一个列表y:

>>> y = [('ab',1), ('cd', 2), ('ef', 3) ]
>>> type(y)
<type 'list'>

我希望得到两个列表['ab', 'cd', 'ef'][1, 2, 3].

I hope to get two lists ['ab', 'cd', 'ef'] and [1, 2, 3].

推荐答案

a,b = zip(*y)

是您所需要的...

或者如果您需要它们作为列表而不是元组

or if you need them as lists and not tuples

a,b = map(list,zip(*y))

这篇关于如何将2元组的列表分成两个列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆