首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将输入的第二个或第三个单词附加到字典中

如何将输入的第二个或第三个单词附加到字典中
EN

Stack Overflow用户
提问于 2020-03-19 06:18:20
回答 1查看 59关注 0票数 0

我正在使用Python

,这是我尝试过的代码:

代码语言:javascript
复制
PIKACHU = {}
command = input("Command: ")
if "Capture" in command:
  command = command.split(' ')
  command.append[1]
if "Query" in command:
  command = command.split(' ')

print(PIKACHU[2])

我想要发生的事情的例子:

代码语言:javascript
复制
 - Command: Capture Pikachu 6
Command: Query Pikachu
Pikachu is level 6.
Command: Query Pikachu
Pikachu is level 6.
Command: Query Eevee
You have not captured Eevee yet.
Command: 

另一个例子:

代码语言:javascript
复制
- Command: Capture Eevee 4
Command: Query Eevee
Eevee is level 4.
Command: Capture Eevee 6
You are already training Eevee!
Command: 

另一个例子:

代码语言:javascript
复制
- Command: Capture Froakie 12
Command: Battle Froakie
Unknown command!
Command: Feed Froakie 5
Unknown command!
Command: Query Froakie
Froakie is level 12.

命令:

我对字典非常陌生,所以我发现很难知道如何把输入中的某些单词添加到字典中。还是名单可能更好?

提前谢谢你。我很困惑。:)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-03-19 07:11:22

不确定我是否正确地理解了你的问题。根据你的例子,这是我认为你想要做的事情。

输入-If命令字符串,将口袋妖怪和级别存储在字典中

输入-If查询字符串,输出带有口袋妖怪名称和级别的字符串。

以下是你如何做到这一点:

代码语言:javascript
复制
Pokemon = {}
command = input("Command: ")
if "Capture" in command:
    command = command.split(' ')
    Pokemon[command[1]] = command[2]
    #stores Pokemon name as key and level as value

if "Query" in command:
     command = command.split(' ')
     if command[1] not in Pokemon: #checks if pokemon is not in dictionary
         print("You have not captured" +  command[1] + "yet.")
     else:
         print(command[1] "is level " + Pokemon[command[1]]) 
         #prints pokemon name and level, which is gotten from dictionary

字典就像哈希映射一样,有一个键值对。因此,这里我创建了一个字典名pokemon,并将pokemon的名称存储为键,级别存储为值。

具有多个同名的口袋妖怪:

代码语言:javascript
复制
Pokemon = {}
command = input("Command: ")
if "Capture" in command:
    command = command.split(' ')
    if command[1] not in Pokemon:
        Pokemon[command[1]] = [command[2]] 
        #if pokemon does not exist in dict yet
        #create new list with first pokemon and store its level
    else:
        Pokemon[command[1]].append(command[2])
        #appends the list value at the pokemon name with the 
        #new pokemon's level

if "Query" in command: 
     command = command.split(' ')
     if command[1] not in Pokemon: #checks if pokemon is not in dictionary
         print("You have not captured" +  command[1] + "yet.")
     else:
         print(command[1] "is level " + Pokemon[command[1]]) 
         #will print a list of pokemon
         #Example: Eevee is level [2,3,5]
         #If you want to specify which pokemon, enter index of list in 
         #Query and get pokemon through it. 
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60751856

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档