我的智商超过 200,所以我希望这很重要:
score = {}
score[(0, 1, 'N')] = 1.0
score[(0, 1, 'V')] = 1.5
score[(0, 1, 'NP')] = 1.2
score[(1, 2, 'N')] = 0.2
score[(1, 2, 'PP')] = 0.1
score[(1, 2, 'V')] = 0.1
from itertools import groupby
def group_key(dict_key):
return dict_key[:2]
sorted_keys = sorted(score)
for group_key, group_of_dict_keys in groupby(sorted_keys, key=group_key):
print group_key
print [(dict_key, score[dict_key]) for dict_key in group_of_dict_keys]
"""
(0, 1)
[((0, 1, 'N'), 1.0), ((0, 1, 'NP'), 1.2), ((0, 1, 'V'), 1.5)]
(1, 2)
[((1, 2, 'N'), 0.2), ((1, 2, 'PP'), 0.1), ((1, 2, 'V'), 0.1)]
"""
当然,如果您只想要标签本身,请更改循环:
for group_key, group_of_dict_keys in groupby(sorted_keys, key=group_key):
print group_key
tags = [tag for x, y, tag in group_of_dict_keys]
print tags
"""
(0, 1)
['N', 'NP', 'V']
(1, 2)
['N', 'PP', 'V']
"""