python中有二进制OR运算符在数组上工作吗?

时间:2015-03-25 09:17:40

标签: python operators

我来自matlab背景到python,我只是想知道python中是否有一个简单的运算符将执行以下功能:

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]

或者我是否必须编写单独的函数来执行此操作?

6 个答案:

答案 0 :(得分:6)

您可以使用列表理解。如果您正在使用Python 2,请使用itertools中的izip

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

或者,@georg在评论中指出您可以导入按位或运算符并将其与map一起使用。这只比列表理解稍快一些。在Python 2中,map不需要用list()包装。

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(其中ab已经转换为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进行其他操作,否则不值得转换。

答案 1 :(得分:4)

如果你的数据是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]

答案 2 :(得分:4)

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

答案 3 :(得分:3)

您可以使用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])

答案 4 :(得分:2)

c = [q|w for q,w in zip(a,b)]
print c
# [1, 1, 0, 1, 0, 1]

答案 5 :(得分:0)

我相信它可以用于多个值,因为 zip 返回一个元组

bitlist = [x & y & z for x, y, z in zip(bitlist, green_mask_h, green_mask_s)]