global ...没有定义python

时间:2018-03-14 08:30:17

标签: python global

我需要在python中通过文本阅读一些文字,我收到了这个错误。 " NameError:全局名称' wordList'没有定义。

i=0
with fitxer as f:
    for line in f:
        for word in line.split():
              wordList[i]=word
              i+1
return wordList

3 个答案:

答案 0 :(得分:1)

您需要先定义wordList。并且您不能在空列表中随机分配索引。您可以轻松地扩展'带有新值的列表。

worldList = []
with fitxer as f:
    for line in f:
        wordList.extend(line.split())
return wordList

答案 1 :(得分:0)

wordList未在范围内实例化为列表。

如果wordList是一个全局变量,函数的开头将需要global wordList 不需要因为对象是突变的

如果列表只在函数范围内,则需要将其实例化为列表。

wordList = []

编辑:正如deceze所指出

在函数本身中,您应该追加到列表,因为索引不存在。

wordList.append(word)

答案 2 :(得分:-2)

在您尝试在循环中使用它或返回它之前,您尚未定义wordList

尝试在wordList = []下方添加i=0,将wordList声明为空列表。

此外,您应该使用wordList.append(i)在此列表中添加单词。