【问题标题】:change and pass a global variable to function Python更改并将全局变量传递给函数 Python
【发布时间】:2013-05-25 11:35:49
【问题描述】:

我有一个递归函数,如下所示,它更改了全局变量,但似乎我无法将更改后的全局变量传递给递归函数,因为错误异常说:

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

【问题讨论】:

    标签: python function variables global nltk


    【解决方案1】:

    您的问题与全球无关。如果没有符合您条件的单词,您只需执行相同的递归调用,从而再次删除 wrec。

    【讨论】:

    • 非常感谢您的回复,但是您能告诉我“再次删除 wrec”是什么意思吗?
    • 如果您使用相同的 w 参数连续两次调用递归函数,则第一次从 wordlist 中删除。您第二次尝试删除但它不存在。那是 Python 抛出异常的时候。
    猜你喜欢
    • 1970-01-01
    • 2022-01-14
    • 2013-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多