【发布时间】:2021-11-24 13:40:23
【问题描述】:
我在下面有以下 for 循环,但我想把它变成一个计算效率更高的变体。我以为我可以通过列表理解来做到这一点,但这给了我以下错误:TypeError: ufunc 'bitwise_and' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
编辑 I:我正在尝试比较 input1 和 input2,如果 input1 大于 input2,则应将差值平方并由缩放器缩放。否则,应为输出分配零值。
我该如何解决这个问题,还有其他方法可以加快速度吗?
# Input variables
input1 = np.array([0.5, 1, 3, 7, 10])
input2 = np.array([0.5, 1.5, 2, 7, 8])
scaler = 3
# For loop
output = np.zeros(len(input1))
for i in range(len(input1)):
if input1[i] > input2[i]:
output[i] = scaler * (input1[i] - input2[i])**2
else:
output[i] = 0
# List comprehension attempt, but gives error.
output = [scaler * (input1-input2)**2 for i in input1 & input2 if input1 > input2]
【问题讨论】:
-
很明显这是一个语法错误,但不知道你实际上想要实现什么,很难说你应该怎么做
标签: python performance for-loop list-comprehension