简体   繁体   中英

How to apply bitwise operator to compare a list of objects

Suppose I have a long list of objects (say, a list of numpy matrices of bool elements) foo = [a, b, c] , that I want to compare with some bitwise operator, to get something like a | b | c a | b | c a | b | c .

If I could use this bitwise operation as a function, say a bitwiseor function, I could simply do this with bitwiseor(*foo) . However, I was not able to find whether the bitwise or can be written in such functional form.

Is there some handy way to handle this kind of problem? Or should I just use a loop to compare all the elements cumulatively?

Using the functional method in operator in combination withfunctools.reduce :

>>> import operator, functools
>>> functools.reduce(operator.or_, [1, 2, 3])
3

numpy has a number of functions that support reducing along an axis. See numpy.bitwise_or and numpy.bitwise_or.reduce .

np.bitwise_or.reduce(your_array)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM