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

时间:2022-02-03 10:38:19

It seems there have been a number of questions surrounding this exercise (48) from Learn Python the Hard Way, yet none answer my question. I have successfully completed the exercise in it's entirety and now wish to refactor it.

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

Before I paste any code let me give you a brief explanation of what the exercise is for. The book provides you with a file (lexicon_tests.py) filled with various test functions and assert_equal statements. The objective is to create another file that contains the code that will allow the various tests to pass using nosetests command from the nose project.

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

I've created a dictionary with the necessary key-value pairs as well as a scan function that will check for int, word, or error. And all my tests pass.

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

Now I would like to shorten up the code. Below is what I've attempted so far:

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

# 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"))

Here is the error I'm receiving currently:

这是我目前收到的错误:

======================================================================
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>

Instead of having multiple lines of code for each key:value entry, is there a way to assign multiple values to a single key entry? The above example 'lexicon = { "direction": ['north', 'south', 'east', 'west', 'down', 'up', 'left', 'right', 'back'] }' does not work. And by all accounts I have been unable to find a clear answer on how to solve this problem.

不是每个键都有多行代码:值输入,有没有办法为单个键条目分配多个值?上面的例子'lexicon = {“direction”:['north','south','east','west','down','up','left','right','back']}'不起作用。从各方面来看,我一直无法找到解决这个问题的明确答案。

Any help is greatly appreciated. Thanks!

任何帮助是极大的赞赏。谢谢!

1 个解决方案

#1


0  

"is there a way to assign multiple values to a single key entry?"

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

You can assign a list, like you are doing in your first lexicon. To quickly search if a word is in that list, you can use word in list like so:

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

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

#1


0  

"is there a way to assign multiple values to a single key entry?"

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

You can assign a list, like you are doing in your first lexicon. To quickly search if a word is in that list, you can use word in list like so:

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

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