5

I have some code in python, that bitwise or-equals b to all the values in an a multidimensional list called a

for i in xrange(len(a)):
    for j in xrange(len(a[i])):
        a[i][j] |= b

My question is, is there any way to write this code using only (map(), filter(), reduce()) without having to use lambdas or any other function definitions like in the example below

map(lambda x: map(lambda y: y | b, x), a)
1
  • 2
    What is the use case for using the higher-order functions map, filter, and reduce without a function parameter? Commented Mar 5, 2012 at 4:23

3 Answers 3

5

I see absolutely no reason why one should ever avoid lambdas or list comprehensions, but here goes:

import operator,functools
a = map(functools.partial(map, functools.partial(operator.or_, b)), a)
Sign up to request clarification or add additional context in comments.

1 Comment

Note that functools.partial is similar to lambda, so IMHO the correct answer is No you can't, as @senderle already wrote: stackoverflow.com/a/9561602/1763602 . About functools.partial vs lambda: stackoverflow.com/a/3252425/1763602
4

map, filter, and reduce all take functions (or at least callables -- i.e. anything with a __call__ method) as arguments. So basically, no. You have to define a function, or a class.

1 Comment

...or, to state the obvious, use a built-in function that is defined elsewhere.
1

Unfortunately Python has no terse currying syntax, so you can't do something like map(b |, x).

I would just use list comprehensions:

[y | b for x in a for y in x]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.