我對Python很陌生,正在通過「Learn Python The Hard Way」Web教程學習。但是由於傳遞單個字符串時遇到問題,我停下了腳步。我能夠通過一個列表OK ...Python:列表迭代可以工作,但單個字符串不會
練習48讓我們對單元測試中的代碼進行反向工程。單元測試是:
def test_directions():
assert_equal(Lexicon.scan("north"), [('direction', 'north')])
我的代碼如下所示:
class Lexicon:
def __init__(self):
self.directions = ['north','south','east','west','down','up','left','right','back']
self.verbs = ['go','stop','kill','eat']
self.stops = ['the','in','of','from','at','it']
self.nouns = ['door','bear','princess','cabinet']
def scan(self, words):
result = []
for i in words:
if i in self.directions:
result.append(('direction', i))
elif i in self.verbs:
result.append(('verb', i))
elif i in self.stops:
result.append(('stop', i))
elif i in self.nouns:
result.append(('noun', i))
else:
try:
result.append(('number', int(i)))
except ValueError:
result.append(('error', i))
return result
運行從Python提示代碼給我下面的結果:
>>> from lexicon import Lexicon
>>> test = Lexicon()
>>> test.directions
['north', 'south', 'east', 'west', 'down', 'up', 'left', 'right', 'back']
>>> words = ['south']
>>> test.scan(words)
[('direction', 'south')]
>>>
>>> test.scan("north")
[('error', 'n'), ('error', 'o'), ('error', 'r'), ('error', 't'), ('error', 'h')]
>>>
,我會很感謝如果有人能指出爲什麼列表被單獨處理不同的字符串?還有我該如何重新編寫我的代碼,以便兩者的處理方式相同?
在此先感謝,奈傑爾。
在第一種情況下,您傳遞了一個帶有單個元素的列表,而在第二種情況下,您傳遞的是字符串本身,這不是預期的輸入參數(因此是不需要的行爲)。 – 2014-10-04 15:09:24
該練習中的'unittest'也顯示了由空格分隔的多個單詞的單個字符串參數 - 您將需要考慮您的方法中的單詞字符串參數。 – wwii 2014-10-04 16:24:48