可能重复: Python中的Transpose/Unzip函数
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.
>>> 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.
基本上,我正在寻找> zip() 函数.
Basically, I'm hunting for inverse operation of zip() function.
推荐答案使用zip(*list):
>>> l = [(1,2), (3,4), (8,9)] >>> list(zip(*l)) [(1, 3, 8), (2, 4, 9)]zip()函数将所有输入中的元素配对,从第一个值开始,然后是第二个值,等等.通过使用*l,您将l中的所有元组应用为单独的参数到zip()函数,因此zip()首先将1与3和8配对,然后将2与4和9配对.这些恰好与列或l的转置很好地对应.
The zip() function pairs up the elements from all inputs, starting with the first values, then the second, etc. By using *l you apply all tuples in l as separate arguments to the zip() function, so zip() pairs up 1 with 3 with 8 first, then 2 with 4 and 9. Those happen to correspond nicely with the columns, or the transposition of l.
zip()产生元组;如果必须具有可变的列表对象,只需map()要列出的元组或使用列表理解来生成列表列表:
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:
map(list, zip(*l)) # keep it a generator [list(t) for t in zip(*l)] # consume the zip generator into a list of lists更多推荐
如何将元组列表解压缩到单个列表中?
发布评论