0
我有一個遞歸函數如下這改變了全局變量,但似乎我不能改變全局變量傳遞給遞歸函數,因爲錯誤異常說:變化,並通過一個全局變量函數的Python
File "forlooptest.py", line 18, in get_final_list
wordList.remove(w)
ValueError: list.remove(x): x not in list
我認爲list.remove(x): x not in list
是因爲全局變量沒有被改變。
有誰能告訴我我該怎麼做?謝謝!
import wordNet
import copy
from __builtin__ import any as b_any
final_list = []
wrec = 'start'
def get_final_list(wordList, w):
'''functions for get the sematically linked words list
traverse and check every word then append to final_list'''
final_list.append(w)
hyplst = wordNet.gethypSet(w)
hyperlst = wordNet.gethyperSet(w)
wordList.remove(w)
for word in wordList:
if (word in hyplst
or word in hyperlst
or b_any(word in x for x in hyplst)
or b_any(word in x for x in hyperlst)):
global wrec
wrec = word
break
get_final_list(wordList, wrec)
return final_list
非常感謝您的回覆,但您能否告訴我「第二次刪除wrec」是什麼意思? – noben
如果您使用相同的w參數對您的遞歸函數進行了兩次連續調用,則首次從wordlist中刪除。第二次嘗試刪除,但它不在那裏。那是Python拋出異常的時候。 – deufeufeu
這很清楚。謝謝。 :) – noben