from collections import Counter
tuples = [('A', 'B'), ('C', 'D'), ('E', 'F'), ('G', 'H'), ('A', 'B'), ('C', 'D')]
counted = Counter(tuples).most_common()
s_t = sorted(counted, key=lambda x: x[0][0])
for key, value in s_t:
print key, value
上記のコードも、タプルの最初の文字列の値に従ってソートします。
コンソール セッション:
>>> from collections import Counter
>>> tuples = [('A', 'B'), ('C', 'D'), ('E', 'F'), ('G', 'H'), ('A', 'B'), ('C', 'D'), ('C', 'D'), ('C', 'D')]
>>> counted = Counter(tuples).most_common()
>>> counted
Out[8]: [(('C', 'D'), 4), (('A', 'B'), 2), (('G', 'H'), 1), (('E', 'F'), 1)]
>>> sorted_tuples = sorted(counted, key=lambda x: x[0][0])
>>> sorted_tuples
Out[10]: [(('A', 'B'), 2), (('C', 'D'), 4), (('E', 'F'), 1), (('G', 'H'), 1)]