Can you apply an operation directly to arguments within map/reduce/filter?

大兔子大兔子 提交于 2021-02-08 13:45:48

问题


map and filter are often interchangeable with list comprehensions, but reduce is not so easily swapped out as map and filter (and besides, in some cases I still prefer the functional syntax anyway). When you need to operate on the arguments themselves, though, I find myself going through syntactical gymnastics and eventually have to write entire functions to maintain readability.

I'll use map to keep the illustration unit-test simple, but please keep in mind that real-life use-cases might be harder to express as a list comprehension.

I've found two messy ways to go about it, but nothing I would ever actually use.

[afunc(*i) for i in aniter] == map(afunc, *zip(*aniter))
[afunc(*i) for i in aniter] == map(lambda i: apply(afunc, i), aniter)

Is there any pithy, elegant way to express the right hand side of these expressions?


回答1:


Check out itertools for tools that will make your life easier.

For example, the code you posted is already available as itertools.starmap.

itertools.starmap(afunc, aniter)

From the documentation:

Make an iterator that computes the function using arguments obtained from the iterable. Used instead of imap() when argument parameters are already grouped in tuples from a single iterable (the data has been “pre-zipped”). The difference between imap() and starmap() parallels the distinction between function(a,b) and function(*c). Equivalent to:

def starmap(function, iterable):
   # starmap(pow, [(2,5), (3,2), (10,3)]) --> 32 9 1000
   for args in iterable:
       yield function(*args)

There are also tons over other goodies hidden in itertools, so I recommend you read through the documentation to see if there is anything else there that you can use. The recipes section also show ways that you can use the functions available in itertools to solve a variety of problems. Even if you can't find a recipe that solves your exact requirements, it's likely that you can use some of the ideas demonstrated as a source of inspiration.



来源:https://stackoverflow.com/questions/11402607/can-you-apply-an-operation-directly-to-arguments-within-map-reduce-filter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!