插入式词典

2024-05-13 23:06:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要对包含一组键和值的字典进行排序,键和值都不同,我需要在导出到文件之前通过插入排序对值进行排序。在

到目前为止,我所能找到的就是人们对多个字典的任意一个列表进行排序,其中所有被排序的键都是相同的。在

我的代码如下:

playerName = ['a','b','c','d','e','f','g','h','i','j','k','l','m']
playerScore = [12,15,31,26,94,13,16,12,11,85,70,14,56]
player = dict(zip(playerName, playerScore))

print(player)

我现在该如何分类?在

谢谢


Tags: 文件代码列表字典排序分类zipdict
2条回答

与其使用字典,不如考虑一下:

playerName = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm']
playerScore = [12, 15, 31, 26, 94, 13, 16, 12, 11, 85, 70, 14, 56] 

player = sorted(zip(playerName, playerScore), key=lambda x: x[0])

print(player)
[('a', 12),
 ('b', 15),
 ('c', 31),
 ('d', 26),
 ('e', 94),
 ('f', 13),
 ('g', 16),
 ('h', 12),
 ('i', 11),
 ('j', 85),
 ('k', 70),
 ('l', 14),
 ('m', 56)]

只需调用python的内置sorted函数,并将lambda函数作为参数传递,这样它就知道要对什么进行排序。在


如果要构造有序字典,可以使用collections.OrderedDict(python<;3.6):

^{pr2}$

它仍然是一个字典,支持所有dict方法:

print(isinstance(player_dict, dict)
True

请注意,python3.6+中的字典在默认情况下是按顺序排列的,因此只需将元组列表从sorted传递到{},您将得到相同的排序结果。在

我认为最好用播放器核心作为键。如果你使用palyerscores作为键,那么你就可以得到这些键,并且可以对键进行排序。然后你就可以找到最佳得分者和最低得分者。在

playerName = ['a','b','c','d','e','f','g','h','i','j','k','l','m']
playerScore = [12,15,31,26,94,13,16,12,11,85,70,14,56]
player = dict(zip(playerScore, playerName))
PList = []
for i in player.keys():
    PList.append(i)
PList.sort()
print(PList)
print(player)

相关问题 更多 >