繁体   English   中英

为什么结果不同,尽管代码完全相同?

[英]Why is the result different ,despite the code is exactly the same?

我想构建一个 function 将两个 numpy arrays 相加成一个新数组,当且仅当不同的索引是相等的。

x = np.array([2,1,1,1])
y=np.array([2,1,0,1])   

overlap = np.zeros(4)
for i in range(0,len(x)):
    if x[i] == y[i]:
        overlap[i]= x[i]+y[i]

print(overlap)
[4. 2. 2. 2.]

这按预期工作。 现在我想定义 function,但输出不同,尽管代码完全相同。

    def sum_overlap(x,y):
       overlap = np.zeros(4)
       for i in range(0,len(x),1):
           if x[i] == y[i]:
              overlap[i] = x[i] + y[i]
              print(overlap)

sum_overlap(x,y)
[4. 0. 0. 0.]
[4. 2. 0. 0.]
[4. 2. 2. 0.]
[4. 2. 2. 2.]

我认为它与迭代器有关,但我无法弄清楚。

您的打印语句在循环中,因此每次调用它都会打印出列表。 将打印语句从循环中取出,但保留在 function 中,您的输出应该相同

工作代码:

def sum_overlap(x,y):
    overlap = np.zeros(4)
    for i in range(0,len(x),1):
        if x[i] == y[i]:
            overlap[i] = x[i] + y[i]
    return overlap
      

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM