Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么';我的代码不能正确创建元组列表吗?_Python_Methods_Tuples - Fatal编程技术网

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']
。这是我希望这个程序总体上做的

  • 接受一个句子
  • 对那个句子进行扫描,并将句子分成不同的单词
  • 让扫描根据几个列表检查句子中的所有单词(这只是对单个列表的第一次测试)
  • 如果在列表中找到一个单词,那么我想创建一个元组,第一个单词是列表的名称,第二个单词是单词
  • 我想为不在列表中的单词创建一个元组,就像前面的一样,但是使用“Error”而不是列表名
  • 我想返回一个名为term的元组列表,其中包含所有不同的单词,它们的列表名或错误在元组的第一部分

  • 此处的这一行缩进过深:

    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)