我正在使用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.命令:
我对字典非常陌生,所以我发现很难知道如何把输入中的某些单词添加到字典中。还是名单可能更好?
提前谢谢你。我很困惑。:)
发布于 2020-03-19 07:11:22
不确定我是否正确地理解了你的问题。根据你的例子,这是我认为你想要做的事情。
输入-If命令字符串,将口袋妖怪和级别存储在字典中
输入-If查询字符串,输出带有口袋妖怪名称和级别的字符串。
以下是你如何做到这一点:
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的名称存储为键,级别存储为值。
具有多个同名的口袋妖怪:
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. https://stackoverflow.com/questions/60751856
复制相似问题