Python 如何压缩列表中的列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4112265/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 14:19:13  来源:igfitidea点击:

How to zip lists in a list

pythonfunctional-programming

提问by Vijay Mathew

I want to zip the following list of lists:

我想压缩以下列表列表:

>>> zip([[1,2], [3,4], [5,6]])
[[1,3,5], [2,4,6]]

This could be achieved with the current zipimplementation only if the list is split into individual components:

zip仅当列表被拆分为单独的组件时,才能使用当前的实现来实现这一点:

>>> zip([1,2], [3,4], [5,6])
   (1, 3, 5), (2, 4, 6)]

Can't figure out how to split the list and pass the individual elements to zip. A functional solution is preferred.

无法弄清楚如何拆分列表并将单个元素传递给zip. 功能性解决方案是优选的。

采纳答案by Mark Byers

Try this:

尝试这个:

>>> zip(*[[1,2], [3,4], [5,6]])
[(1, 3, 5), (2, 4, 6)]

See Unpacking Argument Lists:

请参阅解包参数列表

The reverse situation occurs when the arguments are already in a list or tuple but need to be unpacked for a function call requiring separate positional arguments. For instance, the built-in range() function expects separate start and stop arguments. If they are not available separately, write the function call with the *-operator to unpack the arguments out of a list or tuple:

当参数已经在列表或元组中但需要为需要单独位置参数的函数调用解包时,会发生相反的情况。例如,内置的 range() 函数需要单独的 start 和 stop 参数。如果它们不能单独使用,请使用 *-operator 编写函数调用以将参数从列表或元组中解压缩:

>>> range(3, 6)             # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> range(*args)            # call with arguments unpacked from a list
[3, 4, 5]