Is it possible to apply the operation directly to the arguments in the map / reduce / filter file?

map and filter are often interchangeable with a list, but reduce not as easy to replace as map and filter (and, in addition, in some cases I still prefer the functional syntax), However, when you need to work with the arguments themselves, I am in syntactic gymnastics and, ultimately, must write entire functions to ensure readability.

I use map so that a simple and straightforward block test is simple, but please keep in mind that practical use cases may be more difficult to express as a list comprehension.

I found two messy ways around this, but I wouldn’t really use anything.

 [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 discerning, elegant way to express the right side of these expressions?

+6
source share
1 answer

Check out itertools for tools that 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 evaluates the function using arguments derived from iterable. It is used instead of imap () when the argument parameters are already grouped into tuples from one iterable (the data was "pre-encoded"). The difference between imap () and starmap () is parallel to the difference between functions (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 of other goodies hidden in itertools , so I recommend that you read the documentation to find out if there is anything else you can use. The recipes section also shows how to use the features available in itertools to solve many problems. Even if you cannot find a recipe that solves your exact requirements, you can probably use some of the ideas presented as a source of inspiration.

+11
source

Source: https://habr.com/ru/post/920073/


All Articles