gpt4 book ai didi

带有 np.intc 的 Python 范围

转载 作者:行者123 更新时间:2023-12-04 14:09:07 24 4
gpt4 key购买 nike

昨天我在这里问了一个关于 python range() 的奇怪行为的问题。我不小心使用了 range() 而不是 np.arange()。但取决于输入 int 类型它是否适用于数学运算。这是在一个巨大的背景下,所以我简化了问题。

import numpy as np 

"""
DOES WORK
"""
x1 = np.intc(545)
x2 = np.intc(1048)
x_axis = range(x1, x2)
test = (x_axis - x1) # should throw exception, but works
type(x_axis[0]) # numpy.int32 / intc

"""
DOESNT WORK
"""
t1 = 545
t2 = 1048
t_axis = range(t1, t2)
test2 = (t_axis - t1) # throws TypeError unsupported operand type(s) for -: 'range' and 'int'

背景:使用 intc-datatype 的原因是我的程序执行一些其他任务,如寻峰等,我使用一些列表推导来从计算出的峰值中生成列表。在其他一些步骤之后,我使用了这个峰值列表中的 x1 和 x2(这显然不是一个普通的整数列表)。所以我昨天更改了我的代码并生成了一个新列表,然后发生了异常。我的猜测是 numpy/scipy 内部使用 intc。

有人可以解释这种行为吗?

最佳答案

Python 序列和标量的行为不同于 numpy 一维数组和标量。让我们通过几个基本示例来掌握它的窍门(如果赶时间,可以跳到底部):

# define our test objects
a_range = range(2,6)
a_list = list(a_range)
a_array = np.array(a_list)

# ranges don't add
a_range+a_range
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# TypeError: unsupported operand type(s) for +: 'range' and 'range'

# lists do add but with different semantics ...
a_list+a_list
# [2, 3, 4, 5, 2, 3, 4, 5]

# ... from numpy arrays
a_array+a_array
# array([ 4, 6, 8, 10])

# what happens if we mix types?

# range and list don't mix:
a_range+a_list
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# TypeError: unsupported operand type(s) for +: 'range' and 'list'

# but as soon as there is a numpy object involved it "wins":

a_range+a_array
# array([ 4, 6, 8, 10])

a_list+a_array
# array([ 4, 6, 8, 10])

# How about scalars?

py_scalar = 3
np_scalar = np.int64(py_scalar)

# again, in pure python you cannot add something to a range ...
a_range+py_scalar
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# TypeError: unsupported operand type(s) for +: 'range' and 'int'

# or a list
a_list+py_scalar
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# TypeError: can only concatenate list (not "int") to list

# but you can add a Python or numpy scalar to a numpy object
a_array+py_scalar
# array([5, 6, 7, 8])

a_array+np_scalar
# array([5, 6, 7, 8])

# Now if the scalar is a numpy object, again, it "wins":

a_range+np_scalar
# array([5, 6, 7, 8])

a_list+np_scalar
# array([5, 6, 7, 8])

总而言之,Python 序列和 numpy 一维数组具有不同的语义,特别是对于“+”、“-”或“*”等二元运算符。如果至少一个操作数是一个 numpy 对象(数组或标量),则 numpy 获胜:非 numpy 对象将被转换(平面序列变为一维数组)并且 numpy 语义将适用。

关于带有 np.intc 的 Python 范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65952109/

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