了解字典/列表在石头-布-剪刀程序中的用法吗?

2024-09-28 23:09:39 发布

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

我不明白这到底是什么意思: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]在说什么?你知道吗


Tags: andtextininputreturnifdeflower
1条回答
网友
1楼 · 发布于 2024-09-28 23:09:39

让我们详细看看。你知道吗

for x in rules:

rules中的x是什么?你有x = "rock"x = "scissors"x = "papers"。你知道吗

rules是一个dict,所以其中有键和值。例如,它将值"scissors"附加到键"rock",因此rules["rock"] == "scissors"。你知道吗

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

因此,我们在这里检查播放机a是否获得一个值为播放机b拥有的键(在我们的示例中,它将是a获得"rock"b获得"scissors")。你知道吗

如果是这样,玩家a获胜。你知道吗


不过,你真的需要学习更多关于字典的知识,因为这不仅仅是必要的。查看this以了解dict对象的基础知识。你知道吗

相关问题 更多 >