Itemgetter
使用 itemgetter
將值分組為字典的鍵值對:
from itertools import groupby
from operator import itemgetter
adict = {'a': 1, 'b': 5, 'c': 1}
dict((i, dict(v)) for i, v in groupby(adict.items(), itemgetter(1)))
# Output: {1: {'a': 1, 'c': 1}, 5: {'b': 5}}
這對於像這樣的 lambda
函式是等效的(但更快):
dict((i, dict(v)) for i, v in groupby(adict.items(), lambda x: x[1]))
或者按第二個元素排序元組列表首先將第一個元素排序為次要元素:
alist_of_tuples = [(5,2), (1,3), (2,2)]
sorted(alist_of_tuples, key=itemgetter(1,0))
# Output: [(2, 2), (5, 2), (1, 3)]