【问题标题】:How to fix list comprehension 'bitwise_and' error and optimize for-loop?如何修复列表理解'bitwise_and'错误并优化for循环?
【发布时间】: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


【解决方案1】:

如果您只是尝试使用列表推导优化 for 循环,则以下内容是等效的:

# Input variables
input1 = np.array([0.5, 1, 3, 7, 10])
input2 = np.array([0.5, 1.5, 2, 7, 8])
scaler = 3

# List comprehension
output = [scaler * (x-y)**2 if x>y else 0 for (x,y) in zip(input1,input2)]

编辑:这可能更快,因为 numpy 可以矢量化操作

# Numpy operations
arr = input1-input2
arr = arr.clip(min=0)
output = scaler * arr ** 2

【讨论】:

  • 工作就像一个魅力!
  • @meistef 请采纳答案
  • @Haukland 我需要等待 5 分钟,但会接受。
  • @meistef,尝试使用 numpy 实现
【解决方案2】:

你在做列表压缩错误。

如果你愿意

output = [scaler * (i1-i2)**2 if i1 > i2 else 0 for (i1, i2) in zip(input1, input2)]

print(output)

【讨论】:

  • 这似乎有效!但是,我想添加一个 else 语句,即当 i1 不大于 i2 时,为该索引存储一个值 0。我该如何添加这个?
  • @meistef [f(x) if condition else g(x) for ...]
  • 只要把 if 条件移到返回值,加上 else 0 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-02
  • 2022-12-24
  • 2011-06-15
  • 1970-01-01
  • 2022-11-03
  • 2023-03-11
相关资源
最近更新 更多