简体   繁体   中英

change and pass a global variable to function Python

I have a recursive function as below which changes the global variable but it seems that i cannot pass the changed global variable to the recursive function since the error exceptions says:

File "forlooptest.py", line 18, in get_final_list
        wordList.remove(w)
        ValueError: list.remove(x): x not in list

I think list.remove(x): x not in list is because the global variable hasn't been changed.

Could anyone tell me how can i do this? Thanks!

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

Your issue has nothing to do with global. If there's no word matching your criteria you just do the same recursive call, hence deleting wrec a second time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM