开发者

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

开发者 https://www.devze.com 2023-04-07 11:41 出处:网络
This question already has answers here: Transpose/Unzip Function (inverse of zip)? (14 answers) Closed 4 months ago.
This question already has answers here: Transpose/Unzip Function (inverse of zip)? (14 answers) Closed 4 months ago.

I have a list that looks like this:

my_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 开发者_JAVA百科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.


>>> 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.


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

精彩评论

暂无评论...
验证码 换一张
取 消