Python 如何将元组列表解压缩到单个列表中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12974474/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to unzip a list of tuples into individual lists?
提问by VaidAbhishek
Possible Duplicate:
A Transpose/Unzip Function in Python
可能的重复:
Python 中的转置/解压缩函数
I have a list of tuples, where I want to unzip this list into two independent lists. I'm looking for some standardized operation in Python.
我有一个元组列表,我想将这个列表解压缩成两个独立的列表。我正在寻找 Python 中的一些标准化操作。
>>> l = [(1,2), (3,4), (8,9)]
>>> f_xxx (l)
[ [1, 3, 8], [2, 4, 9] ]
I'm looking for a succinct and pythonic way to achieve this.
我正在寻找一种简洁的 Pythonic 方式来实现这一目标。
Basically, I'm hunting for inverse operation of zip()function.
基本上,我正在寻找zip()函数的逆运算。
采纳答案by Martijn Pieters
Use zip(*list):
使用zip(*list):
>>> l = [(1,2), (3,4), (8,9)]
>>> list(zip(*l))
[(1, 3, 8), (2, 4, 9)]
The zip()functionpairs up the elements from all inputs, starting with the first values, then the second, etc. By using *lyou apply all tuples in las separate argumentsto the zip()function, so zip()pairs up 1with 3with 8first, then 2with 4and 9. Those happen to correspond nicely with the columns, or the transpositionof l.
该zip()功能对向上从所有输入的元件,从所述第一值,则第二等。通过使用*l你申请的所有元组中l作为单独的参数的zip()函数,所以zip()对向上1与3与8第一,然后2用4和9。那些发生在与列,或者很好对应换位的l。
zip()produces tuples; if you must have mutable list objects, just map()the tuples to lists or use a list comprehension to produce a list of lists:
zip()产生元组;如果您必须有可变列表对象,只需map()将元组列表或使用列表理解来生成列表列表:
map(list, zip(*l)) # keep it a generator
[list(t) for t in zip(*l)] # consume the zip generator into a list of lists
回答by VaidAbhishek
If you want a list of lists:
如果你想要一个列表列表:
>>> [list(t) for t in zip(*l)]
[[1, 3, 8], [2, 4, 9]]
If a list of tuples is OK:
如果元组列表没问题:
>>> zip(*l)
[(1, 3, 8), (2, 4, 9)]

