转置/解压缩功能(zip的反函数)? [英] Transpose/Unzip Function (inverse of zip)?

查看:96
本文介绍了转置/解压缩功能(zip的反函数)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含2个项目的元组的列表,我想将它们转换为2个列表,其中第一个包含每个元组的第一项,第二个包含第二个项.

I have a list of 2-item tuples and I'd like to convert them to 2 lists where the first contains the first item in each tuple and the second list holds the second item.

例如:

original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
# and I want to become...
result = (['a', 'b', 'c', 'd'], [1, 2, 3, 4])

有内置的功能吗?

推荐答案

zip 是它自己的逆函数!前提是您使用特殊的*运算符.

zip is its own inverse! Provided you use the special * operator.

>>> zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4)])
[('a', 'b', 'c', 'd'), (1, 2, 3, 4)]

此方法的工作方式是使用以下参数调用zip:

The way this works is by calling zip with the arguments:

zip(('a', 1), ('b', 2), ('c', 3), ('d', 4))

...,因为参数直接传递给了zip(在转换为元组之后),因此不必担心参数的数量太大.

… except the arguments are passed to zip directly (after being converted to a tuple), so there's no need to worry about the number of arguments getting too big.

这篇关于转置/解压缩功能(zip的反函数)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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