python 元组分组并排序

# -*- coding: utf-8 -*-
# @Time    : 2018/8/31 14:32
# @Author  : cxa
# @File    : glomtest.py
# @Software: PyCharm
from operator import itemgetter
from itertools import groupby

a= (('a', 1),('a', 2),('b', 1),('b', 5),('c', 6),('c', 2),('d', 1),('d', 21))
b=list(a)
b.sort(key=itemgetter(0,1))
data_2=groupby(b,itemgetter(0))

for k,v in data_2:
    print(k,list(v))

输出

a [('a', 1), ('a', 2)]
b [('b', 1), ('b', 5)]
c [('c', 2), ('c', 6)]
d [('d', 1), ('d', 21)]
原文地址:https://www.cnblogs.com/c-x-a/p/9674312.html