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)
weeb
  • 1,939
  • 4
  • 18
  • 29

3 Answers3

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)
phihag
  • 278,196
  • 72
  • 453
  • 469
  • Note that `functools.partial` is similar to `lambda`, so IMHO the correct answer is *No you can't*, as @senderle already wrote: http://stackoverflow.com/a/9561602/1763602 . About `functools.partial` vs `lambda`: http://stackoverflow.com/a/3252425/1763602 – Marco Sulla Feb 24 '16 at 10:39
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.

senderle
  • 145,869
  • 36
  • 209
  • 233
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]
Daniel Lubarov
  • 7,796
  • 1
  • 37
  • 56