簡體   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