python中是否有一个适用于数组的二元OR运算符? [英] is there a binary OR operator in python that works on arrays?
问题描述
我是从 matlab 背景到 python 的,我只是想知道 python 中是否有一个简单的运算符可以执行以下功能:
I have come from a matlab background to python and i am 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 would i have to write a separate function to do that?
推荐答案
您可以使用列表推导式.如果您使用的是 itertools 中的 izip
蟒蛇 2.
You could use a list comprehension. Use izip
from itertools if you're using Python 2.
c = [x | y for x, y in zip(a, b)]
或者,@georg 在评论中指出您可以导入按位或运算符并将其与 map
一起使用.这仅比列表理解略快.map
在 Python 2 中不需要用 list()
包裹.
Alternatively, @georg pointed out in a comment that you can import the bitwise or operator and use it with map
. This is only slightly faster than the list comprehension. map
doesn't need wrapped with list()
in 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 数组):
NumPy (where a
and b
have already been converted to numpy arrays):
$ 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 进行其他操作,否则不值得转换.
Conclusion: Unless you need NumPy for other operations, it's not worth the conversion.
这篇关于python中是否有一个适用于数组的二元OR运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!