首页 > 解决方案 > 如何在字典中无序搜索?

问题描述

我正在尝试制作一个石头剪刀布游戏。
我正在制作一个函数来检查谁赢了。
但我不想发表大量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语句。

我想将其部署在网络摄像头馈送的计算机视觉项目中,因此速度也很重要。

标签: pythonpython-3.xdictionary

解决方案


只是一个小模:

>>> 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

(虽然这只显示了获胜的手,而不是谁赢了......我真的不想扩展它,因为无论如何我都会使用我的第一个解决方案。)


推荐阅读