如何将元组列表解压缩到单个列表中?

编程入门 行业动态 更新时间:2024-10-19 15:27:48
本文介绍了如何将元组列表解压缩到单个列表中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

可能重复: 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

更多推荐

如何将元组列表解压缩到单个列表中?

本文发布于:2023-11-05 08:09:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1560318.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:解压缩   如何将   列表   列表中

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!