[英]What is common pratice with return statements in functions?
我無法理解何時使用return
函數。 在下面的函數中,我的直覺是return
語句應該在那里返回修改后的列表,但我的助教說是多余的,我不太明白為什么。 任何關於何時正確使用return
語句和常見做法的澄清將不勝感激。
p = [2,0,1]
q = [-2,1,0,0,1,0,0,0]
p1 = [0,0,0,0]
#Without return statement
def drop_zeros1(p_list):
"""drops zeros at end of list"""
i = 0
while i < len(p_list):
if p_list[-1]==0:
p_list.pop(-1)
else:
break
#With return statement
def drop_zeros(p_list):
"""drops zeros at end of list"""
i = 0
while i < len(p_list):
if p_list[-1]==0:
p_list.pop(-1)
else:
return p_list
break
另外為什么在列表 p1 上使用時輸出不一致,它只在應該刪除所有零時刪除最后一個 0?
非常感謝,
約定是函數要么改變給它的參數,要么返回結果,但不改變參數。
這是為了防止您的函數的用戶執行此操作:
template = [1, 2, 0, 0]
shorter = drop_zeros(template)
print ("input was ", template, " and output was ", shorter)
他們會期望這個輸出:
輸入為 [1, 2, 0, 0] 輸出為 [1, 2]
......但驚訝地看到:
輸入為 [1, 2],輸出為 [1, 2]
因此,為了避免這種情況,您可以:
不返回修改后的參數,而是None
。 這樣上面的代碼將輸出...and output was None
,用戶會理解該函數不是為了返回結果而設計的。
返回結果,但確保參數保留其原始內容
所以在你的情況下,你可以這樣做:
def drop_zeros(p_list):
"""drops zeroes at end of list, in-place"""
while p_list and p_list[-1] == 0:
p_list.pop()
請注意, else
可以更好地集成到while
條件中。 不再需要顯式地break
。 此外.pop()
不需要 -1 作為參數:它是默認值。
如果您更喜歡返回結果的函數,那么邏輯應該有些不同:
def drop_zeros(p_list):
"""returns a copy of the list without the ending zeroes"""
for i in range(len(p_list)-1, -1, -1):
if p_list[i] != 0:
return p_list[0:i+1]
return []
現在該代碼旨在執行以下操作:
template = [1, 2, 0, 0]
shorter = drop_zeros(template)
print ("input was ", template, " and output was ", shorter)
# input was [1, 2, 0, 0] and output was [1, 2]
你的助教是對的,因為在 python 中被稱為aliasing ,所以返回是多余的。
基本上,在您的函數中, p_list
是對調用函數時傳入的任何列表的引用(不是副本)。 由於您使用pop
,它在提取元素時就地改變列表,因此p_list
將被修改,並且此修改將在函數外部可見:
drop_zeros(q) # from here, in the function, p_list is q (as in, exactly the same object)
print(q)
印刷
[-2,1,0,0,1]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.