为什么这两个字符串不一样,字典和输入?

时间:2017-11-24 20:57:16

标签: python dictionary

在代码中:

skill = input("Which skill would you like to increase by 1 ?: ")
            for x in abilities:
                if x.lower() == skill.lower():
                    abilities[x] += 1
                    break
            print("Sorry, I don't see that skill...")

和字典是:

abilities = {
    "STR" : 10,
    "DEX" : 10,
    "CON" : 10,
    "INT" : 10,
    "WIS" : 10,
    "CHR" : 10 }

然后,当输入字符串“STR”被输入时,我得到响应,告诉我字符串不相同。

据我所知,他们是?这里有一个非常简单的错误,我不小心查看了,或者这种事情是否存在某种规则?

2 个答案:

答案 0 :(得分:2)

for x in abilities:
    if x.lower() == skill.lower():
        abilities[x] += 1
        break
print("Sorry, I don't see that skill...")

无论循环结果如何,都会打印错误消息。

只需在else循环中添加for即可

for x in abilities:
    if x.lower() == skill.lower():
        abilities[x] += 1
        break
else:
    # called when for loop ended without hitting break or return
    print("Sorry, I don't see that skill...")

然而,这是一种非常低效的计算方式,你不是按原样使用字典,而是作为tuples的列表,所以线性搜索,非常低效

使用(没有循环):

skill = skill.upper()  # so casing matches the keys
if skill in abilities:
  abilities[x] += 1

答案 1 :(得分:1)

你知道abilities'键都是大写字符串,因此您应该将输入转换为大写:

skill = input("Which skill would you like to increase by 1 ?: ").upper()
if skill in abilities:
    abilities[x] += 1
else:
    print("Sorry, I don't see that skill...")
相关问题