Is there a binary OR operator in python that works with arrays?

I came from matlab background in python, and I'm just wondering if there is a simple operator in python that will perform the following function:

a = [1, 0, 0, 1, 0, 0]
b = [0, 1, 0, 1, 0, 1]
c = a|b
print c
[1, 1, 0, 1, 0, 1]

or do I need to write a separate function for this?

+4
source share
5 answers

You can use list comprehension. Use izipfrom itertools if you are using Python 2.

c = [x | y for x, y in zip(a, b)]

@georg , map. , . map list() Python 2.

import operator
c = list(map(operator.or_, a, b))

:

$ python -m timeit -s "a = [1, 0, 0, 1, 0, 0]; b = [0, 1, 0, 1, 0, 1]" \
> "[x | y for x, y in zip(a, b)]"

1000000 loops, best of 3: 1.41 usec per loop

$ python -m timeit -s "a = [1, 0, 0, 1, 0, 0]; b = [0, 1, 0, 1, 0, 1]; \
> from operator import or_" "list(map(or_, a, b))"
1000000 loops, best of 3: 1.31 usec per loop

NumPy

$ python -m timeit -s "import numpy; a = [1, 0, 0, 1, 0, 0]; \
> b = [0, 1, 0, 1, 0, 1]" "na = numpy.array(a); nb = numpy.array(b); na | nb"

100000 loops, best of 3: 6.07 usec per loop

NumPy ( a b numpy):

$ python -m timeit -s "import numpy; a = numpy.array([1, 0, 0, 1, 0, 0]); \
> b = numpy.array([0, 1, 0, 1, 0, 1])" "a | b"

1000000 loops, best of 3: 1.1 usec per loop

. NumPy , .

+6

numpy, , :

In [42]:

a = np.array([1, 0, 0, 1, 0, 0])
b = np.array([0, 1, 0, 1, 0, 1])
c = a|b
print(c)
[1 1 0 1 0 1]
Out[42]:
[1, 1, 0, 1, 0, 1]
+4

map(lambda (a,b): a|b,zip(a,b))

+4
source

You can use numpy.bitwise_or

>>> import numpy
>>> a = [1, 0, 0, 1, 0, 0]
>>> b = [0, 1, 0, 1, 0, 1]
>>> numpy.bitwise_or(a,b)
array([1, 1, 0, 1, 0, 1])
+3
source
c = [q|w for q,w in zip(a,b)]
print c
# [1, 1, 0, 1, 0, 1]
+2
source

All Articles