python - 深层嵌套字典/ map 情况所需的替代数据结构

标签 python data-structures

一些数据背景:一些不同的游戏正在玩,每个游戏都有很多玩家。每场比赛都由数轮组成,在每一轮中,每个参与的玩家都会采取行动。我在这里试图做的是在内存中构建一个数据结构,用于存储玩家在所有正在玩的游戏中所采取的个人 Action 的完整历史。

一个明显的结构是一个深度嵌套的字典/ HashMap ,其中每个 game_id 映射到多个 player_id,每个 player_id被映射到不同的round_number,每个round_number被映射到一个action

换句话说,game_id:player_id:round_number:action。另一方面,我也可以使用 game_id:round_number:player_id:action

出现问题 当我尝试访问上述数据结构以用于不同的分析目的时。例如,如果我想知道玩家在给定游戏的特定回合中所做的所有 Action ,那么使用 game_id:player_id:round_number:action 是不方便的。相反,如果我想知道特定玩家在给定游戏过程中所做的所有 Action ,那么使用 game_id:round_number:player_id:action 也同样不方便。不幸的是,就我而言,我需要经常问这两个问题。

我想知道是否有一个单一的数据结构可以存储这样的数据,并且可以方便地访问如上所述的玩家级和回合级数据。如果重要的话,实现将使用 Python。

编辑:一些人推荐使用内存中的 sqlite 数据库来处理此类关系查询。然而,它的性能对我来说可能是个问题,如下所述:SQLite Performance Benchmark -- why is :memory: so slow...only 1.5X as fast as disk?

最佳答案

一种方法是将数据存储在字典中,但保留索引 以允许快速访问数据的各种 View 。你可以用一个类来构造它,或者只是函数。这是它的jist(未经测试):

from collections import defaultdict

game_dict = {}  # keyed by (game, player, round) tuple
game_player_ix = defaultdict(list)
game_round_ix = defaultdict(list)

def add_action(game, player, round):
    game_dict[(game, round, player)] = action # track the action in the main dict
    game_player_ix[(game, player)].append(round)  # keep an index for lookups by player
    game_round_ix[(game, round)].append(player) # another index for lookups by round

def get_all_player_actions(game, player):
    return (game_dict[(game,player,round)] for round in game_round_ix[(game, player)]) # iterator

def get_all_round_actions(game, round):
    return (game_dict[(game,player,round)] for player in game_player_ix[(game, round)]) # iterator

关于python - 深层嵌套字典/ map 情况所需的替代数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10857851/

相关文章:

python - 在Linux上使用Python模块编译GEOS 3.6.2

python 在 64 位上安装 pywinauto

Python CSV 导入在前 20 万行后花费太多时间

c - 实现二叉搜索树

c++ - Algorithm文件解决方案中的错误c2784、c2780和c2676?

python - 将一个键值从字典列表转换为列表

python - 如何使用 sklearn 在 Python 中将 N*M 矩阵居中

java - 是否有一个很好的 Java 对象来保存 2D double 网格?

java - 拆分数组 - 我的实现正确吗?

java - 使用 BinaryTree 将字符编码为二进制