Skip to main content
 首页 » 编程设计

python之LPTHW 练习 48 帮助之使用列表中的元组

2025年05月04日12thcjp

我目前正在通过 LPTHW 并且我要到 excercise 48这是我第一次碰壁。

这是给我的测试用例的第一部分

from nose.tools import * 
from ex48 import lexicon 
 
def test_direction(): 
    assert_equal(lexicon.scan("north"), [('direction', 'north')]) 
    result = lexicon.scan("north south east") 
    assert_equal(result, [('direction', 'north'), 
                          ('direction', 'south'), 
                          ('direction', 'east')]) 

This question has been asked here before ,我注意到我目前的解决方案与 answer provided by robbyt 完全相同.但它仍然不起作用。

def scan(thewords): 
 
    directions = [('direction', 'north'), ('direction', 'south'), ('direction', 'east')] 
 
    thewords = thewords.split() 
    sentence = [] 
 
    for i in thewords: 
        if i in directions: 
            sentence.append(('direction', i)) 
 
        else: 
            sentence.append(('error', i)) 
 
 
    return sentence 

所以问题是:在获取输入(thewords)之后,我如何正确地搜索元组列表,然后返回它所属的特定元组?

在此先感谢您提供任何类型的答案和建议,真的坚持这个。

请您参考如下方法:

受@Evee 第一个解决方案(感谢)的启发,这是我通过所有测试的解决方案。也许它使用的代码比第二种解决方案更多,但它消除了定义的唯一方法之外的循环。

class Lexicon(object): 
    def __init__(self): 
        self.mapping = { 
              'direction':  ['north', 'south', 'east', 'west'], 
              'verb':       ['go', 'kill', 'eat'], 
              'stop':       ['the', 'in', 'of'], 
              'noun':       ['door', 'bear', 'princess', 'cabinet'] 
              } 
        self.mapping_categories = self.mapping.keys() 
 
    def scan(self, input): 
        self.result = [] 
 
        for word in input.split(): 
            try: 
                self.result.append(('number', int(word))) 
            except ValueError: 
                for category, item in self.mapping.items(): 
                    if word.lower() in item: 
                        found_category = category 
                        break 
                    else: 
                        found_category = 'error' 
                self.result.append((found_category, word)) 
 
        return self.result 
 
lexicon = Lexicon()