LPTHW 练习 48 帮助 - 列表中的元组操作
我现在正在学习《通过艰难的方式学Python》,已经到了第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')])
这个问题之前有人问过,我发现我现在的解决方案和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)后,我该如何正确地在元组列表中搜索,然后返回它所属于的特定元组呢?
非常感谢任何形式的回答和建议,我真的被这个问题困住了。
5 个回答
2
使用字典会让事情变得简单又快速。看看这段代码吧。
directions = ['north', 'south', 'east', 'west', 'down', 'up', 'left', 'right', 'back']
verbs = ['go','stop','kill','eat']
stop_words = ['the', 'in', 'of', 'from', 'it']
nouns = ['door','bear','princess','cabinet']
lexicons = {}
for key in directions:
lexicons[key] = 'direction'
for key in verbs:
lexicons[key] = 'verb'
for key in stop_words:
lexicons[key] = 'stop'
for key in nouns:
lexicons[key] = 'noun'
def scan(sentence):
tuples = []
words = sentence.split()
for word in words:
try:
tuples.append((lexicons[word],word))
except KeyError:
if word.isdigit():
tuples.append(('number',int(word)))
else:
tuples.append(('error',word))
return tuples
3
受到@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()
2
所以多亏了Thomas K和ed的提示,我终于完成了这个练习。现在回头看,我有点懊恼自己,因为其实这件事看起来是如此简单……
directions = ['north', 'south', 'east', 'west', 'down', 'up', 'down', 'right']
verbs = ['go', 'stop', 'kill', 'eat']
stops = ['the', 'in', 'at', 'of', 'from', 'at', 'it']
nouns = ['door', 'bear', 'princess', 'cabinet']
def scan(thewords):
thewords = thewords.split()
sentence = []
for i in thewords:
if i in directions:
sentence.append(('direction', i))
elif i in verbs:
sentence.append(('verb', i))
elif i in stops:
sentence.append(('stop', i))
elif i in nouns:
sentence.append(('noun', i))
elif i.isdigit():
sentence.append(('number', convert_number(i)))
else:
sentence.append(('error', i))
return sentence
def convert_number(s):
try:
return int(s)
except ValueError:
return None