【问题标题】:Is there an elegant way of preventing numpy from slapping a dtype on empty lists?有没有一种优雅的方法可以防止 numpy 在空列表上拍打 dtype?
【发布时间】:2019-06-01 20:49:41
【问题描述】:

考虑以下示例,它可能看起来很傻,但实际上是现实世界烦恼的精简版:

import numpy as np
a = np.zeros(5, int)
b = [*range(5)]
for i in reversed(range(5)):
    a[:i] += b[:i]

# Traceback (most recent call last):
#  File "<stdin>", line 2, in <module>
# TypeError: Cannot cast ufunc add output from dtype('float64') to dtype('int64') with casting rule 'same_kind'                                                                                                         

此异常在最后一次迭代中引发,因为 numpy 无法再推断 rhs 列表的正确 dtype。

当然,显式检查空操作数很容易

for i in reversed(range(5)):
    if b[:i]:
        a[:i] += b[:i]

但我想知道是否有更优雅的解决方案。

【问题讨论】:

  • 一个可能可以通过改变 Numpy.只是要明确一点,您希望有什么行为?第一个代码 sn-p 应该像第二个代码一样?
  • for i in reversed(range(1,5)):??
  • a[:i] += np.array(b[:i], dtype=a.dtype)
  • @wwii 我的错,因为我做了一个太简单的例子,但在现实世界的代码中,操作数的大小并不那么容易控制/预测。
  • 可能很难对这个问题给出明确的答案,因为您可能有理由拒绝一些明显的变通办法。例如,您可以在进行就地加法之前将加数转换为与a 具有相同类型的数组:a[:i] += np.array(b[:i], dtype=a.dtype)。但不要这样做,因为在开头将b 转换为数组会更有效。

标签: python list numpy type-inference


【解决方案1】:

只是想分享我最后的目标。至少它很短:

for i in reversed(range(5)):
    a[:i] += b[:i] or 0

a
# array([0, 3, 4, 3, 0])

【讨论】:

    猜你喜欢
    • 2021-08-14
    • 2022-11-13
    • 2012-04-09
    • 2010-12-20
    • 2022-12-24
    • 2010-12-10
    • 1970-01-01
    • 2015-10-10
    • 2019-01-26
    相关资源
    最近更新 更多