python - 如何在字典中无序搜索?
问题描述
我正在尝试制作一个石头剪刀布游戏。
我正在制作一个函数来检查谁赢了。
但我不想发表大量if-else
声明。我正在考虑一些逻辑来减少这些。
我想出了以下实现
moves_dict = {('R', 'P'): 'P',
('R', 'S'): 'R',
('S', 'P'): 'S'}
user_comp = ['User', 'Computer']
# item_check = (userMove, computerMove)
move_check = ('R', 'S')
if moves_dict.get(move_check):
print('Move exists')
print(
f"Winner : {user_comp[move_check.index(moves_dict.get(move_check))]}")
elif moves_dict.get(move_check[::-1]):
print("Rev move exist")
print(
f"Winner : {user_comp[move_check.index(moves_dict.get(move_check[::-1]))]}")
else:
print('Tie')
我首先消除了 Tie 的可能性,然后继续获取 value( winner move
),然后在键中查找它的索引。获得索引后,我只是从user_comp
.
如您所见,键值对基本上是move:winner move
. 我同意代码正朝着不可读的状态发展,但是
我想知道是否有办法我不必使用该elif
语句。
我想将其部署在网络摄像头馈送的计算机视觉项目中,因此速度也很重要。
解决方案
只是一个小模:
>>> for user in 'RPS':
for computer in 'RPS':
winner = ('RPS'.find(user) - 'RPS'.find(computer)) % 3
print(f'{user=} {computer=} =>',
('Tie', 'User wins', 'Computer wins')[winner])
user='R' computer='R' => Tie
user='R' computer='P' => Computer wins
user='R' computer='S' => User wins
user='P' computer='R' => User wins
user='P' computer='P' => Tie
user='P' computer='S' => Computer wins
user='S' computer='R' => Computer wins
user='S' computer='P' => User wins
user='S' computer='S' => Tie
要回答有关在字典中无顺序搜索的标题问题,您可以使用frozenset
键而不是元组:
>>> moves_dict = {frozenset('RP'): 'P',
frozenset('RS'): 'R',
frozenset('SP'): 'S'}
>>> for user in 'RPS':
for computer in 'RPS':
winner = moves_dict.get(frozenset((user, computer)))
print(f'{user=} {computer=} =>', winner)
user='R' computer='R' => None
user='R' computer='P' => P
user='R' computer='S' => R
user='P' computer='R' => P
user='P' computer='P' => None
user='P' computer='S' => S
user='S' computer='R' => R
user='S' computer='P' => S
user='S' computer='S' => None
(虽然这只显示了获胜的手,而不是谁赢了......我真的不想扩展它,因为无论如何我都会使用我的第一个解决方案。)
推荐阅读
- java - 使用@Endpoint springboot 返回 html 内容
- python - 如何使用密码加密创建 pyc?
- amazon-web-services - AWS S3 删除所有对象或在给定日期范围内
- sql - 字符串列中单词的频率
- python - 如何腌制通过pybind11用c ++编写的对象?
- javascript - 如何创建 Vue 3 自定义元素,包括子组件样式?
- java - 当我们尝试配置 JMX 的远程访问时,本地 JMX 调用失败
- javascript - @sendGrid - 来自经过身份验证的发件人的 403“禁止访问”错误
- python - 需要 Blob 检测方面的帮助,Python 中的 openCV
- javascript - 修改查询以接受 JSON 数组