itertools模块之groupby

itertools模块之groupby

from itertools import groupby

lst = [2, 8, 11, 25, 43, 6, 9, 29, 51, 66]


def gb(num):
    if num <= 10:
        return 'less'
    elif num >= 30:
        return 'great'
    else:
        return 'middle'


print({k:list(g) for k, g in groupby(sorted(lst), key=gb)})
#{'less': [2, 6, 8, 9], 'middle': [11, 25, 29], 'great': [43, 51, 66]}

你可能感兴趣的:(python,开发语言)