gpt4 book ai didi

python - 单个 numpy 数组元素的引用

转载 作者:太空狗 更新时间:2023-10-30 02:04:08 26 4
gpt4 key购买 nike

假设我有一个类似 numpy 的数组

x = np.arange(10)

是否有可能以某种方式创建对单个元素的引用,即

y = create_a_reference_to(x[3])
y = 100
print x
[ 0 1 2 100 4 5 6 7 8 9]

最佳答案

您不能创建对单个元素的引用,但您可以获得对该单个元素的 View :

>>> x = numpy.arange(10)
>>> y = x[3:4]
>>> y[0] = 100
>>> x
array([0, 1, 2, 100, 4, 5, 6, 7, 8, 9])

你不能做前者的原因是python中的一切都是引用。通过执行 y = 100,您正在修改 y 指向的内容 - 而不是它的值。

如果你真的想,你可以get that behaviour on instance attributes by using properties .请注意,这是唯一可能的,因为 python 数据模型 specifies additional operations while accessing class attributes - 不可能为变量获得这种行为

关于python - 单个 numpy 数组元素的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23654088/

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