问题
I have a of list of bitwise elements, e.g. [1,1,1], and I want to do a bitwise OR operation between every element in the list. So, e.g.
for [1,1,1] do
1 | 1 | 1 = 1
or for [1,17,1] do
1 | 17 | 1 = 17
How can I do this without looping? Numpy's bitwise_or only seems to work on 2 arrays. Is there a bitwise & or | that works on every element, similar to sum, or np.mean? Thanks.
回答1:
This works for numpy reduce:
>>> ar = numpy.array([1,17,1])
>>> numpy.bitwise_or.reduce(ar)
17
回答2:
You can use reduce with operator.ior:
>>> from operator import ior
>>> lst = [1, 17, 1]
>>> reduce(ior, lst)
17
And as suggested by @DSM in comments the numpy equivalent will be:
>>> import numpy as np
>>> arr = np.array(lst)
>>> np.bitwise_or.reduce(arr)
17
回答3:
Without importing anything, neither numpy nor operator.ior, as suggested in the other answers:
a = [1,17,1]
reduce(lambda x,y: x | y, a)
Edit: However, when I benchmarked different options, this was faster:
a = [1,17,1]; b = 0
for x in a: b |= x
This second option also has the advantage that it works in Python 3, from which reduce has been eliminated (although it can still be imported from functools).
来源:https://stackoverflow.com/questions/25796158/bitwise-operations-between-elements-in-a-list