我试图编写一个带变量的程序,其中包含一个字典,其中键是一个单词字符串,值是字符串列表。每个字符串都是单词/键的定义。
我想要做的是询问用户一个字;如果它不在词典中。然后我显示一条错误信息,如果是,则打印出每个定义,从1开始编号。
我无法理解如何在不同的行上调用不同的定义并对它们进行编号。这就是我到目前为止所做的:
def Dict(webdict):
word_user = raw_input('Word ==> ')
i =0
if word_user in webdict:
while i <= len(webdict['word_user']):
print str(i+1) + '.', webdict['word_user'][i]
i+=1
else:
print '"' + word_user + '"', 'not found in webdict.'
Dict(webdict)
一些示例输出:
Word ==> python
1. a large heavy-bodied nonvenomous constrictor snake occurring throughout the Old World tropics
2. a high-level general-purpose programming language
Word ==> constrictor
Word “constrictor” not found in webster
谢谢!
答案 0 :(得分:2)
当您对webdict
编制索引时,密钥应为word_user
,而不是'word_user'
。后者是字符串文字,而不是用户输入的内容。
您的while
循环超过列表末尾。将<=
更改为<
,或只使用for
圈enumerate
。
def Dict(webdict):
word_user = raw_input('Word ==> ')
i =0
if word_user in webdict:
while i < len(webdict[word_user]):
print str(i+1) + '.', webdict[word_user][i]
i+=1
else:
print '"' + word_user + '"', 'not found in webdict.'
webdict = {"Python": ["A cool snake", "A cool language"]}
Dict(webdict)
或者
def Dict(webdict):
word_user = raw_input('Word ==> ')
if word_user in webdict:
for i, definition in enumerate(webdict[word_user], 1):
print str(i+1) + '.', definition
else:
print '"' + word_user + '"', 'not found in webdict.'
webdict = {"Python": ["A cool snake", "A cool language"]}
Dict(webdict)
结果:
Word ==> Python
1. A cool snake
2. A cool language