gpt4 book ai didi

python - 如何构建高级切片的逻辑表达式

转载 作者:太空宇宙 更新时间:2023-11-04 09:15:08 26 4
gpt4 key购买 nike

我正在尝试找出一种更简洁的方法来执行以下操作:

import numpy

a = np.array([1,2,4,5,1,4,2,1])

cut = a == (1 or 2)
print cut

[ True False False False True False False True]

以上当然是一个简化的例子。表达式 (1 or 2) 可以很大也可以很复杂。首先,我想概括一下:

cutexp = (1 or 2)
cut = a == cutexp

也许,cutex 可以变成一个函数或其他东西,但我不确定从哪里开始寻找。

最佳答案

你也可以试试 numpy.in1d .说

>>> a = np.array([1,2,4,5,1,4,2,1])
>>> b = np.array([1,2]) # Your test array
>>> np.in1d(a,b)
array([ True, True, False, False, True, False, True, True], dtype=bool)

关于python - 如何构建高级切片的逻辑表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10464740/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com