【问题标题】:Different function outputs for integers and numpy arrays整数和 numpy 数组的不同函数输出
【发布时间】:2022-01-06 22:18:28
【问题描述】:

我无法理解,为什么我在以下两种情况下得到不同的值:

-案例1:

def myfunc(a,b,c):
    xx = a+b
    yy = b+c
    return xx, yy

q,w = myfunc(1,2,3)

print(q,w)

Output 1: 3 5

-案例2:

import numpy as np

q=w=np.zeros(3)

def myfunc(a,b,c):
    xx = a+b
    yy = b+c
    return xx, yy


for i in range(3):
    q[i],w[i] = myfunc(1,2,3)

print(q,w)

Output 2: [5. 5. 5.] [5. 5. 5.]

在第二种情况下,两个数组的条目都等于 5。谁能解释一下,为什么?

【问题讨论】:

    标签: python arrays numpy


    【解决方案1】:

    我不会谈论第一种情况,因为它简单明了。对于第二种情况,您定义了变量 q 和 w 如下

    q=w=np.zeros(3)

    在这种情况下,您在 q 中所做的任何更改都将应用于 w,因为它们的 q 和 w 具有相同的地址。

    当你运行这个时:

    q[i],w[i] = myfunc(1,2,3)

    q[i] 获得值 3,w[i] 获得值 5,由于 q 和 w 具有相同的地址,q[i] 也将获得值 5。这就解释了为什么你每次都有 5 个。

    如果你想解决它,将变量定义行从:

    q=w=np.zeros(3)
    

    到:

    w=np.zeros(3)
    q=np.zeros(3)
    

    【讨论】:

    • 更准确地说,qw 都是对np.zeros(3) 创建的同一个对象的引用。 (Python 中没有“地址”的概念。)
    • 谢谢,这有帮助。我以为我会通过使用 q=w=np.zeros(3) 而不是 w=np.zeros(3) q=np.zeros(3) 来节省空间,但不知道它们会被分配到相同的内存地址.
    • @chepner,是的,这是有道理的!谢谢!
    • @numpy 没有“他们”;您只创建了 一个 对象,然后定义了两个引用两个它。简单的赋值 never 在 Python 中创建一个副本。请务必阅读nedbatchelder.com/text/names.html
    猜你喜欢
    • 2011-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-30
    • 2012-12-29
    • 2013-08-22
    • 2014-01-22
    • 2011-08-17
    相关资源
    最近更新 更多