尝试通过向字典中的键添加多个值来重构。 (练习48艰难学习Python

时间:2018-05-04 02:29:33

标签: python python-3.x powershell

似乎围绕这个练习(48)有一些问题来自Learn Python the Hard Way,但没有人回答我的问题。我已经成功地完成了整个练习,现在希望重构它。

在我粘贴任何代码之前,让我简要解释一下这个练习的内容。本书为您提供了一个文件(lexicon_tests.py),其中包含各种测试函数和assert_equal语句。目标是创建另一个文件,其中包含允许使用nose项目中的nosetests命令传递各种测试的代码。

我创建了一个包含必要键值对的字典以及一个检查int,word或error的扫描函数。我的所有测试都通过了。

现在我想缩短代码。以下是我到目前为止所尝试的内容:

# from collections import defaultdict

# What I'm trying to do

lexicon = {
    "direction": ['north', 'south', 'east', 'west', 'down', 'up', 'left', 'right', 'back']
}

''' *What I've already done*
lexicon = {
    "north": 'direction',
    "south": 'direction',
    "east": 'direction',
    "west": 'direction',
    "down": 'down',
    "up": 'direction',
    "left": 'direction',
    "right": 'direction',
    "back": 'direction',
    "go": 'verb',
    "stop": 'verb',
    "kill": 'verb',
    "eat": 'verb',
    "the": 'stop',
    "in": 'stop',
    "of": 'stop',
    "from": 'stop',
    "at": 'stop',
    "it": 'stop',
    "bear": 'noun',
    "door": 'noun',
    "princess": 'noun',
    "cabinet": 'noun',
    "0": 'number',
    "1": 'number',
    "2": 'number',
    "3": 'number',
    "4": 'number',
    "5": 'number',
    "6": 'number',
    "7": 'number',
    "8": 'number',
    "9": 'number',
}
''' 

''' *Not sure how to incorporate this with my code below or if it will work*
lexicon = defaultdict(list)

for k, v in 1:
    d1[k].append(v)

d = dict((k, tuple(v)) for k, v in d1.iteritems())
'''

# Scan Method - This works fine
def scan(sentence):
    results = []
    words = sentence.split()
    for word in words:
        try:
            temp = int(word)
            word_type = "number"
            results.append((word_type, temp))
        except ValueError:
            word_type = lexicon.get(word)
            if word_type == None:
                results.append(('error', word))
            else:
                results.append((word_type, word))
    return results

if __name__ == '__main__':
    print(scan("ASDFADFASDF"))

以下是我目前收到的错误:

======================================================================
FAIL: tests.lexicon_tests.test_directions
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\blalonde\AppData\Local\Programs\Python\Python36-32\lib\site-packages\nose-1.3.7-py3.6.egg\nose\case.py", line 198, in runTest
    self.test(*self.arg)
  File "C:\lpthw\projects\ex48\skeleton\tests\lexicon_tests.py", line 6, in test_directions
    assert_equal(lexicon.scan("north"), [('direction', 'north')])
AssertionError: Lists differ: [('error', 'north')] != [('direction', 'north')]

First differing element 0:
('error', 'north')
('direction', 'north')

- [('error', 'north')]
?     ^^ ^

+ [('direction', 'north')]
?    +++ ^^^ ^


----------------------------------------------------------------------
Ran 1 test in 0.032s

FAILED (failures=1)
PS C:\lpthw\projects\ex48\skeleton>

有没有办法为每个键:值条目分配多行代码,有没有办法为单个键条目分配多个值?以上示例' lexicon = {     "方向":[' north',' south',' east',' west','向下','向上','左','对','返回'] }'不起作用。从各方面来看,我一直无法找到解决这个问题的明确答案。

非常感谢任何帮助。谢谢!

1 个答案:

答案 0 :(得分:0)

"有没有办法为单个键条目分配多个值?"

您可以指定一个列表,就像您在第一个词典中所做的那样。要快速搜索某个单词是否在该列表中,您可以使用word in list,如下所示:

for word in words:
    if word in lexicon["direction"]:
        word_type = "direction"
    # You can also use get()
    elif word in lexicon.get("number"):
        word_type = "number"
    else:
        word_type = "err"
    results.append((word_type, word))
return results