解压嵌套列表以获取map()的参数 [英] Unpack nested list for arguments to map()

查看:65
本文介绍了解压嵌套列表以获取map()的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我敢肯定有办法做到这一点,但我一直找不到.说我有:

I'm sure there's a way of doing this, but I haven't been able to find it. Say I have:

foo = [
    [1, 2],
    [3, 4],
    [5, 6]
]

def add(num1, num2):
    return num1 + num2

然后我如何使用map(add, foo),以便它在第一次迭代中传递num1=1num2=2,即先执行add(1, 2),然后再进行add(3, 4),等等?

Then how can I use map(add, foo) such that it passes num1=1, num2=2 for the first iteration, i.e., it does add(1, 2), then add(3, 4) for the second, etc.?

  • 尝试map(add, foo)显然会在第一次迭代中执行add([1, 2], #nothing)
  • 尝试map(add, *foo)在第一次迭代中执行add(1, 3, 5)
  • Trying map(add, foo) obviously does add([1, 2], #nothing) for the first iteration
  • Trying map(add, *foo) does add(1, 3, 5) for the first iteration

我希望在第一次迭代中像map(add, foo)这样执行add(1, 2).

I want something like map(add, foo) to do add(1, 2) on the first iteration.

预期输出:[3, 7, 11]

推荐答案

听起来您需要 starmap :

It sounds like you need starmap:

>>> import itertools
>>> list(itertools.starmap(add, foo))
[3, 7, 11]

这会为您从列表foo中解压缩每个参数[a, b],并将它们传递给函数add.与itertools模块中的所有工具一样,它返回一个迭代器,您可以使用list内置函数使用该迭代器.

This unpacks each argument [a, b] from the list foo for you, passing them to the function add. As with all the tools in the itertools module, it returns an iterator which you can consume with the list built-in function.

从文档中

当参数参数已从单个可迭代项的元组中分组时(而不是数据已预压缩"),而不是使用map(). map()starmap()之间的区别与function(a,b)function(*c)之间的区别平行.

Used instead of map() when argument parameters are already grouped in tuples from a single iterable (the data has been "pre-zipped"). The difference between map() and starmap() parallels the distinction between function(a,b) and function(*c).

这篇关于解压嵌套列表以获取map()的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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