如何在列表中压缩列表 [英] How to zip lists in a list

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

问题描述

我想压缩以下列表:

I want to zip the following list of lists:

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

只有当列表被分割时,才能通过当前的 zip 实现来实现。转换为单个组件:

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

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

不知道如何分割列表并将各个元素传递给 zip 。一个功能性的解决方案是首选。

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

推荐答案

试试这个:

Try this:

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

请参阅解包参数列表


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

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(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]

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

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