例如,我有一本字典:
Edern 38
Pellam 34
Ban 32
Lionel 30
Geraint 30
Brangaine 28
Erec 28
Guiron 28
Fisher 28
Elyan 28
Segwarides 26
在这种情况下输出将是:
Edern 38
Pellam 34
Ban 32
Geraint 30
Lionel 30
Brangaine 28
Elyan 28
Erec 28
Fisher 28
Guiron 28
Segwarides 26
我想按字母顺序对具有相同值的键进行排序,但是不要触摸具有不同键的元素?怎么实现这个?
答案 0 :(得分:3)
如果您将名称 - 数字对表示为两项目元组的列表,则可以使用groupby
将类似编号的项目组合在一起,并在内部对每个组进行排序,而不会影响组顺序。
import itertools
items = [
("Edern", 38),
("Pellam", 34),
("Ban", 32),
("Lionel", 30),
("Geraint", 30),
("Brangaine", 28),
("Erec", 28),
("Guiron", 28),
("Fisher", 28),
("Elyan", 28),
("Segwarides", 26)
]
result = []
for k,v in itertools.groupby(items, lambda item: item[1]):
result.extend(sorted(v))
print result
结果:
[
('Edern', 38),
('Pellam', 34),
('Ban', 32),
('Geraint', 30),
('Lionel', 30),
('Brangaine', 28),
('Elyan', 28),
('Erec', 28),
('Fisher', 28),
('Guiron', 28),
('Segwarides', 26)
]
...如果你真的需要dict形式的这些项目,你可以用它们制作一个OrderedDict,如下:
from collections import OrderedDict
d = OrderedDict(result)
答案 1 :(得分:0)
您似乎希望通过减少数值进行排序。所以这对你有用:
d = {'Edern':38,
'Pellam':34,
'Ban':32,
'Lionel':30,
'Geraint':30,
'Brangaine':28,
'Erec':28,
'Guiron':28,
'Fisher':28,
'Elyan':28,
'Segwarides':26}
# build a dictionary that maps the numbers to all the keys that have that value
scored = {}
for k,v in d.items():
if v not in scored:
scored[v] = []
scored[v].append(k)
for k in sorted(scored, reverse=True):
for v in sorted(scored[k]):
print("{} {}".format(v, k))
输出:
Edern 38
Pellam 34
Ban 32
Geraint 30
Lionel 30
Brangaine 28
Elyan 28
Erec 28
Fisher 28
Guiron 28
Segwarides 26
当然,这是一个单行代码:
for k,v in sorted(list(d.items()), key=lambda t: (-1*t[1], t[0])):
print("{} {}".format(k, v))
输出:
Edern 38
Pellam 34
Ban 32
Geraint 30
Lionel 30
Brangaine 28
Elyan 28
Erec 28
Fisher 28
Guiron 28
Segwarides 26