Python 为什么';我的代码不能正确创建元组列表吗?
当我通过Python 为什么';我的代码不能正确创建元组列表吗?,python,methods,tuples,Python,Methods,Tuples,当我通过lexicon.scan('north-south-east')时,我希望返回给我[('direction','north'),('direction','south'),('direction','east')]。相反,我得到的是['north']。这是我希望这个程序总体上做的 接受一个句子 对那个句子进行扫描,并将句子分成不同的单词 让扫描根据几个列表检查句子中的所有单词(这只是对单个列表的第一次测试) 如果在列表中找到一个单词,那么我想创建一个元组,第一个单词是列表的名称,第二个单
lexicon.scan('north-south-east')
时,我希望返回给我[('direction','north'),('direction','south'),('direction','east')]
。相反,我得到的是['north']
。这是我希望这个程序总体上做的
此处的这一行缩进过深:
direction = ['north', 'south', 'east', 'west', 'down', 'up', 'left', 'right', 'back']
class Lexicon(object):
def scan(self, sentence):
self.sentence = sentence
self.words = self.sentence.split()
self.term = []
for word in self.words:
if word in direction:
part = ('direction','%s' % word)
self.term.append(word)
return self.term
lexicon = Lexicon()
它是for
循环主体的一部分,因此循环过早返回。把它放低一级
您还可以使用列表理解:
return self.term
这:
应该是这样的:
self.term.append(word)
您正在丢弃部分,而不是将其添加到self.term
另外,您是从循环内部而不是在循环之后执行return
ing操作,您需要将return
语句删除一个级别。以下是工作代码:
self.term.append(part)
输出:
for word in self.words:
if word in direction:
part = ('direction','%s' % word)
self.term.append(part)
return self.term
在其他答案的基础上,我想补充一点,这不是获得两个集合交集的最佳方法。为什么不直接使用
我觉得这更清晰、更有效。FWIW,为了提高效率,我在里面放了一个direction=set(direction)
。你确定句子、单词和术语需要成为实例变量吗?如果不需要存储局部变量,最好只使用它们。
for word in self.words:
if word in direction:
part = ('direction','%s' % word)
self.term.append(part)
return self.term
[('direction', 'north'), ('direction', 'south'), ('direction', 'east')]
class Lexicon(object):
def bar(self, sentence):
return set(sentence.split()) & set(direction)