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

2024-06-16 17:29:30 发布

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

我正在使用Python

这是我尝试过的代码:

PIKACHU = {}
command = input("Command: ")
if "Capture" in command:
  command = command.split(' ')
  command.append[1]
if "Query" in command:
  command = command.split(' ')

print(PIKACHU[2])

我希望发生的事情的示例:

 - 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: 

另一个例子:

- Command: Capture Eevee 4
Command: Query Eevee
Eevee is level 4.
Command: Capture Eevee 6
You are already training Eevee!
Command: 

另一个例子:

- Command: Capture Froakie 12
Command: Battle Froakie
Unknown command!
Command: Feed Froakie 5
Unknown command!
Command: Query Froakie
Froakie is level 12.

命令:

我对字典非常不熟悉,因此我发现很难知道如何使用输入将某些单词附加到字典中。或者列表是否更好

先谢谢你。我很困惑


Tags: inyouifisquerylevelcommand例子
1条回答
网友
1楼 · 发布于 2024-06-16 17:29:30

不确定我是否正确理解了你的问题。根据你的例子,以下是我认为你正在尝试做的事情

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

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

以下是您将如何做到这一点:

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

字典就像hashmaps一样,有一个键值对。因此,我在这里创建了一个字典名pokemon,并将pokemon的名称存储为键,将level存储为值

使用多个同名口袋妖怪:

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. 

相关问题 更多 >