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

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

问题描述

我确定有一种方法可以做到这一点,但我一直找不到.说我有:

foo = [[1, 2],[3, 4],[5, 6]]def add(num1, num2):返回 num1 + num2

那么我如何使用 map(add, foo) 使其通过 num1=1, num2=2 进行第一次迭代,即,它执行 add(1, 2),然后 add(3, 4) 为第二个,依此类推?

  • 在第一次迭代中尝试 map(add, foo) 显然是 add([1, 2], #nothing)
  • 尝试 map(add, *foo) 对第一次迭代执行 add(1, 3, 5)

我想要像 map(add, foo) 这样的东西在第一次迭代时做 add(1, 2) .

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

解决方案

听起来你需要 星图:

<预><代码>>>>导入迭代工具>>>列表(itertools.starmap(添加,foo))[3, 7, 11]

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

来自文档:

<块引用>

当参数参数已经从单个可迭代对象分组到元组中时(数据已经预压缩"),用于代替 map().map()starmap() 的区别与 function(a,b)function(*c) 的区别类似.

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

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.?

  • 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

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

Expected output: [3, 7, 11]

解决方案

It sounds like you need starmap:

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

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.

From the documents:

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天全站免登陆