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]
在说什么?
解决方案
让我们来详细看看。
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
(在我们的示例中,它将是a
gets"rock"
和b
gets "scissors"
。
如果是这样,玩家a
获胜。
不过,您确实需要了解更多有关词典的信息,因为这非常重要。检查此以了解dict
对象的基础知识。
推荐阅读
- google-sheets - 查询公式替换过滤器
- swiftui - 在 ObservedObject 中操作 EnvironmentObject 而不更新整个视图
- flutter - 集团状态未更新
- r - 无法在 R 中执行 t.test()
- docker - 如何提前向主机写入文件,然后启动Docker容器?
- excel - 记录更改列中的单元格值
- python - 编写一个对同一类的两个实例执行算术运算的方法
- kubernetes - ActiveMQ 的通用过滤器基于过滤器消费消息
- python - 使用循环打开和处理带有 csv 的 txt 文件
- python - 用于查找将分配项目 ID 的存储桶的算法