转置/解压缩功能(zip 的反函数)? [英] Transpose/Unzip Function (inverse of zip)?
本文介绍了转置/解压缩功能(zip 的反函数)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 2 项元组列表,我想将它们转换为 2 个列表,其中第一个包含每个元组中的第一个项目,第二个列表包含第二个项目.
例如:
original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]#我想成为...结果 = (['a', 'b', 'c', 'd'], [1, 2, 3, 4])
是否有内置函数可以做到这一点?
解决方案
zip
是它自己的逆!前提是您使用了特殊的 * 运算符.
它的工作方式是使用参数调用 zip
:
zip(('a', 1), ('b', 2), ('c', 3), ('d', 4))
...除了参数直接传给zip
(转成元组后),所以不用担心参数个数过大.
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.
For example:
original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
# and I want to become...
result = (['a', 'b', 'c', 'd'], [1, 2, 3, 4])
Is there a builtin function that does that?
解决方案
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)]
The way this works is by calling zip
with the arguments:
zip(('a', 1), ('b', 2), ('c', 3), ('d', 4))
… 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屋!
查看全文