[英]Recursively going through list and compare with a value (python)
任務是通過一個列表對go,將其與一個值進行比較,然后返回該值出現的次數。 比較有效,當我找到匹配值時,我想將其保存在列表中。 然后我想得到那個列表的長度。 問題是每次我再次調用 function 時,列表都會重置,我該如何避免呢?
def count_occurences(values, value):
matched_values = []
if values:
if values[0] == value:
matched_values.append(values[0])
count_occurences(values[1:], value)
else:
count_occurences(values[1:], value)
else:
return 0
return len(matched_values)
count_occurences([1, "one", 2, "two", "two", 3, "three", "three", "three"], "two")
在這種情況下,預期的 output 將是:2。
正如@juanpa.arrivillaga 在評論中所說,您正在將matched_values
初始化為每次調用都清空列表,因此您沒有有效地返回任何內容。
腳本可以簡化,例如:
def count_occurences(values, value):
if values:
return (values[0] == value) + count_occurences(values[1:], value)
return 0
n = count_occurences([1, "one", 2, "two", "two", 3, "three", "three", "three"], "two")
print(n)
印刷:
2
您可以通過簡單地將matched_values
分配移到function 之外來解決您的直接問題,如下所示。
matched_values = []
def count_occurences(values, value):
if values:
if values[0] == value:
matched_values.append(values[0])
count_occurences(values[1:], value)
else:
count_occurences(values[1:], value)
else:
return 0
return len(matched_values)
count_occurences([1, "one", 2, "two", "two", 3, "three", "three", "three"], "two")
然而,這段代碼確實提出了比它回答的問題更多的問題。 大概您將其作為學習練習進行,因為您無需特殊的 function 或遞歸即可輕松完成此操作。 所以考慮到這一點,我會問你:
matched_values
的意義何在? 根據定義,它只是重復的同一個條目,因此它不會添加任何信息而不是只知道匹配的數量考慮到這些,您可能會考慮這樣的事情,它消除了列表並且不涉及突變和副作用。
def count_occurences(values, value):
if values:
if values[0] == value:
return 1 + count_occurences(values[1:], value)
else:
return count_occurences(values[1:], value)
else:
return 0
(這與上面 Andrej Kesely 建議的簡化基本相同)
matched_values = []
def count_occurences(values, value, matched_values):
if values:
if values[0] == value:
matched_values.append(values[0])
count_occurences(values[1:], value, matched_values)
else:
count_occurences(values[1:], value, matched_values)
else:
return 0
return len(matched_values, matched_values)
count_occurences([1, "one", 2, "two", "two", 3, "three", "three", "three"], "two", matched_values)
每次調用遞歸 function count_occurences
時都會重置該列表,因為您在 function 的開頭使用以下行重新創建了該列表: matched_values = []
。 這將創建一個新變量matched_values
,它指向memory 中的新位置,並且無法訪問上一輪找到的內容。
在調用 function 之前初始化此空列表可確保每次 function 運行時都會訪問 memory 中的相同位置。 每個遞歸調用都將在同一個列表上運行,並且您不會丟失信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.