首页 > 解决方案 > 了解在剪刀石头布程序中字典/列表的这种用法吗?

问题描述

我不明白这到底在说什么:a.lower() == x and b.lower() == rules[x]:

rules = {'rock':'scissors', 'scissors':'paper', 'paper':'rock'}

def checkResult(a, b):
    if a.lower() == b.lower():
        return 'Draw'
    for x in rules:
        if a.lower() == x and b.lower() == rules[x]:
            return 'Player one wins'
    else:
        return 'Player two wins'

def plyerInputCheck(player):
    text = "Player {}, type your choice (Rock, Scissors, Paper): ".format(player)
    playerChoice = input(text)
    while playerChoice.lower() not in rules:
        print("Wrong input, try again!")
        playerChoice = input(text)
    return playerChoice

while True:
    a = plyerInputCheck("One")
    b = plyerInputCheck("Two")
    print(checkResult(a, b))
    answer = input("Play again?")
    if answer.lower() in ("n", "no"):
        break

我得到了 a.lower() == x 部分,但是 b.lower() == rules[x] 到底是什么,特别是rules[x]在说什么?

标签: python

解决方案


让我们来详细看看。

for x in rules:

里面都有x什么rules?你有x = "rock"和。x = "scissors"x = "papers"

rules是 a dict,所以里面有键和值。例如,它具有"scissors"附加到键的值"rock",所以rules["rock"] == "scissors"

    if a.lower() == x and b.lower() == rules[x]:
        return 'Player one wins'

因此,我们在这里检查玩家是否a获得了一个具有玩家所拥有的值的键b(在我们的示例中,它将是agets"rock"bgets "scissors"

如果是这样,玩家a获胜。


不过,您确实需要了解更多有关词典的信息,因为这非常重要。检查以了解dict对象的基础知识。


推荐阅读