简体   繁体   English

解压嵌套列表以获取map()的参数

[英]Unpack nested list for arguments to 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

Then how can I use map(add, foo) such that it passes num1=1 , num2=2 for the first iteration, ie, it does add(1, 2) , then add(3, 4) for the second, etc.? 然后,如何使用map(add, foo)使其在第一次迭代中传递num1=1num2=2 ,即它确实执行add(1, 2) ,然后执行add(3, 4)进行第二次迭代, num2=2 。?

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

I want something like map(add, foo) to do add(1, 2) on the first iteration. 我希望像map(add, foo)这样的东西在第一次迭代时执行add(1, 2)

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

It sounds like you need starmap : 听起来您需要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 . 这会为您从列表foo解压缩每个参数[a, b] ,并将它们传递给函数add As with all the tools in the itertools module, it returns an iterator which you can consume with the list built-in function. itertools模块中的所有工具一样,它返回一个迭代器,您可以使用list内置函数使用它。

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”). 当参数参数已经从单个可迭代项的元组中分组时(数据已“预压缩”),而不是map() )。 The difference between map() and starmap() parallels the distinction between function(a,b) and function(*c) . map()starmap()之间的区别starmap() function(a,b)function(*c)之间的区别。

try this: 尝试这个:

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

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

print(map(lambda x: add(x[0], x[1]), foo))

There was another answer with a perfectly valid method (even if not as readable as ajcr's answer), but for some reason it was deleted. 还有一个答案是完全有效的方法(即使不像ajcr的答案那样可读),但是由于某种原因,它被删除了。 I'm going to reproduce it, as it may be useful for certain situations 我将重现它,因为它在某些情况下可能有用

>>> map(add, *zip(*foo))
[3, 7, 11]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM