[英]Python function prints output but cannot seem to return it correctly or call it after
我只是試圖追加一個數組,如果它為空並返回更新后的數組。 通過執行以下操作,如果數組不是空白,則可以使數組完全恢復正常,但是對我而言,我無法在else部分中正確返回它。
我可以打印它並將其顯示為輸出,我在做什么錯?
import numpy as np
W = np.array([])
def intitialise_W(W):
if W.size > 0:
W = W
return W
else:
fix = np.array([0.15,0.2,0.25,0.3])
W = np.append(W,fix)
print(W) #Works fine
return W
intitialise_W(W)
print(W) #produces W = [] not W = [0.15, 0.2, 0.25, 0.3] as expected
謝謝
完全不相關(這實際上應該是注釋,但是無法在注釋中發布格式化的代碼,所以...):“ initialize_W()”函數有一些無用的東西和潛在問題
def initialise_W(W):
if W.size > 0:
W = W # => this line is totally useless
return W # => you have one return here and...
else:
fix = np.array([0.15,0.2,0.25,0.3])
W = np.append(W,fix)
return W # you have another return here
實際上,您想要的是:“如果W為空,則將其初始化(否則無需執行任何操作),然后在兩種情況下均返回W”。 這可以用更簡單,更易於閱讀和維護的方式表示:
def initialise_W(W):
if W.size == 0:
fix = np.array([0.15,0.2,0.25,0.3])
W = np.append(W,fix)
return W
您沒有保存從函數返回的值。 改成:
W = intitialise_W(w)
然后就可以了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.