class wordlist:
def is_within(word):
return 3 <= (len(word)) <= 5
def truncate_by_length(wordlist):
return filter(is_within, wordlist)
newWordlist = truncate_by_length(['mark', 'daniel', 'mateo', 'jison'])
print newWordList
基本上,它的作用是,给定单词长度的最小值和最大值(在给定的示例中分别为 3 和 5),它应该打印给定长度内的新单词列表原始长度。例如上面的例子,给定单词 mark、daniel、mateo 和 jison,它应该打印仅包含 mark、mateo 和 jison 的新列表。
每当我运行它时,我都会收到以下信息:
Traceback (most recent call last):
File "C:/Users/Makoy/Documents/AMC 125/sample.py", line 1, in <module>
class wordlist:
File "C:/Users/Makoy/Documents/AMC 125/sample.py", line 6, in wordlist
newWordlist = truncate_by_length(['mark', 'daniel', 'mateo', 'jison'])
File "C:/Users/Makoy/Documents/AMC 125/sample.py", line 5, in truncate_by_length
return filter(is_within, wordlist)
NameError: global name 'is_within' is not defined
如果我听起来很菜鸟之类的,我很抱歉,但我一个月前才开始学习 Python,而且我是一个完全的初学者。提前致谢。
最佳答案
如果您在类方法定义中调用类方法,则需要调用“self”(因此,在示例中为 self.is_within)。类方法的第一个参数也应该是“self”,它指的是该类的实例。查看Dive into Python以获得一个很好的解释。
class wordlist:
def is_within(self, word):
return 3 <= (len(word)) <= 5
def truncate_by_length(self,wordlist):
return filter(self.is_within, wordlist)
wl = wordlist()
newWordList = wl.truncate_by_length(['mark', 'daniel', 'mateo', 'jison'])
print newWordList
关于Python 编程 : Global name 'is_within' is not defined. 我正在使用列表过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14309598/