Unpacking a list / tuple of pairs into two lists / tuples [duplicate]

依然范特西╮ 提交于 2019-12-17 03:46:52

问题


Possible Duplicate:
A Transpose/Unzip Function in Python

I have a list that looks like this:

list = (('1','a'),('2','b'),('3','c'),('4','d'))

I want to separate the list in 2 lists.

list1 = ('1','2','3','4')
list2 = ('a','b','c','d')

I can do it for example with:

list1 = []
list2 = []
for i in list:
   list1.append(i[0])
   list2.append(i[1])

But I want to know if there is a more elegant solution.


回答1:


>>> source_list = ('1','a'),('2','b'),('3','c'),('4','d')
>>> list1, list2 = zip(*source_list)
>>> list1
('1', '2', '3', '4')
>>> list2
('a', 'b', 'c', 'd')

Edit: Note that zip(*iterable) is its own inverse:

>>> list(source_list) == zip(*zip(*source_list))
True

When unpacking into two lists, this becomes:

>>> list1, list2 = zip(*source_list)
>>> list(source_list) == zip(list1, list2)
True

Addition suggested by rocksportrocker.




回答2:


list1= ( x[0] for x in source_list )
list2= ( x[1] for x in source_list )


来源:https://stackoverflow.com/questions/7558908/unpacking-a-list-tuple-of-pairs-into-two-lists-tuples

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!