最近,我在“艰难的学习Python3”中完成了练习48的代码挑战。我正在寻找任何反馈,我的解决方案和任何改进的想法!
完整的任务可以找到这里:
该项目涉及到测试代码,并创建一个脚本,从中工作。测试代码可以找到这里 (不是我的上传)。
它通过了所有的测试,但在其他解决方案后,我怀疑我的解决方案。我的解决方案有效吗?
def scan(sentence):
rebuild = []
directions = ['north', 'south', 'east']
verbs = ['go', 'kill', 'eat']
stops = ['the', 'in', 'of']
nouns = ['bear', 'princess']
split_line = sentence.split()
for word in split_line.copy():
try:
if int(word):
rebuild.append(("number", int(word)))
split_line.remove(word)
except ValueError:
pass
for word in split_line:
if word in directions:
rebuild.append(("direction", word))
elif word in verbs:
rebuild.append(("verb", word))
elif word in stops:
rebuild.append(("stop", word))
elif word in nouns:
rebuild.append(("noun", word))
else:
rebuild.append(("error", word))
return rebuild发布于 2020-04-12 11:27:15
3的
for循环这将使用Python的字典将数据重新构造为键值格式。这将允许您将单词"type“作为键,并查找键的条目中有哪些单词。整个if-elif-elif块可以被削减为一个for循环。这使您可以扩展到更多的word类型,而不需要编写更多的if else语句。for循环不会自动捕获错误,因此可以使用else语句。这将在for循环没有达到中断时运行--这意味着没有任何单词满足键的值。
def scan(sentence):
rebuild = []
word_types = {
"directions": ['north', 'south', 'east'],
"verbs": ['go', 'kill', 'eat']
"stops": ['the', 'in', 'of'],
"nouns": ['bear', 'princess']
}
split_line = sentence.split()
for word in split_line[:]:
try:
if int(word):
rebuild.append(("number", int(word)))
split_line.remove(word)
except ValueError:
pass
for word in split_line:
for key, value in word_types.items():
if word in value:
rebuild.append(key,word)
break
else:
rebuild.append(("error", word))我还使用[:]来表示复制列表,但是使用.copy()是可以的。
https://codereview.stackexchange.com/questions/240355
复制相似问题