Python字典, 键, 和字符串

2024-06-16 19:14:45 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我要做的是要求用户输入一个单词;如果它不在dict中,则显示一条错误消息,如果是,则打印每个定义,从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

谢谢你!你知道吗


Tags: 字符串in程序定义not单词dict编号
1条回答
网友
1楼 · 发布于 2024-06-16 19:14:45
  1. 索引webdict时,键应该是word_user,而不是'word_user'。后者是字符串文本,而不是用户键入的任何内容。

  2. 你的while循环超过了列表的末尾。将<=更改为<,或者只使用带有enumeratefor循环。

你知道吗

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

相关问题 更多 >