weeb
weeb

Reputation: 1991

Python: using map() without lambdas on a multidimensional array/list

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)

Upvotes: 5

Views: 7420

Answers (3)

Daniel Lubarov
Daniel Lubarov

Reputation: 7924

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]

Upvotes: 1

phihag
phihag

Reputation: 287885

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)

Upvotes: 5

senderle
senderle

Reputation: 151007

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.

Upvotes: 4

Related Questions