【问题标题】:Python Dictionaries, Keys, and StringsPython 字典、键和字符串
【发布时间】:2015-05-01 15:13:00
【问题描述】:

我正在尝试编写一个程序,该程序接受一个包含字典的变量,其中键是一个单词字符串,值是字符串列表。每个字符串都是单词/键的定义。

我想做的是向用户询问一个词;如果它不在字典中。然后我显示一条错误消息,如果是,则打印出每个定义,从 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

谢谢!

【问题讨论】:

    标签: python function dictionary key


    【解决方案1】:
    1. 当您索引webdict 时,键应该是word_user,而不是'word_user'。后者是字符串文字,而不是用户键入的任何内容。

    2. 您的while 循环超出了列表的末尾。将&lt;= 更改为&lt;,或者只使用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
    

    【讨论】:

    • enumerate 有一个起始编号,因此 +1 是不必要的。 i=0 也是一个遗留物。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-05
    • 2019-06-26
    • 2013-07-02
    • 2020-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多