如何将元组列表解压缩到单个列表中? [英] How to unzip a list of tuples into individual lists?

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

问题描述

可能重复:
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()首先将138配对,然后将249配对.这些恰好与列或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

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

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