Skip to main content
 首页 » 编程设计

python之Python 字典中的数据重排算法

2025年05月04日9cmt

在 Python 中,我有以下命令:

players = {'player_1': 'data_a', 
     'player_2': 'data_b', 
     'player_3': 'data_c', 
     'player_4': 'data_d', 
     'player_5': 'data_e', 
     'player_6': 'data_f'} 

旋转字典最有效的方法是什么?

所需的算法应将新的“player_1”作为输入,并相应地重新排列字典。

示例:

algorithm('player_4') 

将返回以下字典:

{'player_1': 'data_d', 
 'player_2': 'data_e', 
 'player_3': 'data_f' 
 'player_4': 'data_a', 
 'player_5': 'data_b', 
 'player_6': 'data_c', 
 } 

编辑 当遍历字典时,我使用 sorted 方法中的构建。因此,python dict 未排序 OOTB 并不重要。字典中的数据仍然需要重新排列。

编辑 2: 我在下面使用 sorted 的示例。

for player, data in sorted(players.items()): 
     make_move(player, data) 
     if is_interrupted(player): 
         # The game was interrupted, and we need to start the next round with the player who was interrupted.  
         # This is where I need to rearrange the dict! 

请您参考如下方法:

只需创建键和值的排序列表,然后旋转键列表,并重新构建字典。

def rotate(players, top): 
    keys, vals = zip(*sorted(players.items())) 
    idx = keys.index(top) 
    keys = keys[idx:] + keys[:idx] 
    return dict(zip(keys, vals)) 
 
# test 
 
players = { 
    'player_1': 'data_a', 
    'player_2': 'data_b', 
    'player_3': 'data_c', 
    'player_4': 'data_d', 
    'player_5': 'data_e', 
    'player_6': 'data_f', 
} 
 
new_players = rotate(players, 'player_4') 
for k in sorted(new_players): 
    print(k, new_players[k]) 

输出

player_1 data_d 
player_2 data_e 
player_3 data_f 
player_4 data_a 
player_5 data_b 
player_6 data_c 

如果你想就地修改原始的dict对象,你可以这样做。我在函数调用前后打印 dict 的 id 以验证它是同一个对象。

def rotate(players, top): 
    keys, vals = zip(*sorted(players.items())) 
    idx = keys.index(top) 
    keys = keys[idx:] + keys[:idx] 
    players.clear() 
    players.update(zip(keys, vals)) 
 
# test 
 
players = { 
    'player_1': 'data_a', 
    'player_2': 'data_b', 
    'player_3': 'data_c', 
    'player_4': 'data_d', 
    'player_5': 'data_e', 
    'player_6': 'data_f', 
} 
 
print(id(players)) 
rotate(players, 'player_4') 
print(id(players)) 
for k in sorted(players): 
    print(k, players[k]) 

输出

3072628692 
3072628692 
player_1 data_d 
player_2 data_e 
player_3 data_f 
player_4 data_a 
player_5 data_b 
player_6 data_c