I have a group of items marked as item_labels = [('a', 3), ('b', 2), ('c', 1), ('d', 3), ('e', 2), ('f', 3)]
I want to sort them by group size. for example, label 3 has a size of 3, and label 2 has a size of 2 in the above example.
I tried using a combination of groupby and sorted but did not work.
In [162]: sil = sorted(item_labels, key=op.itemgetter(1)) In [163]: sil Out[163]: [('c', 1), ('b', 2), ('e', 2), ('a', 3), ('d', 3), ('f', 3)] In [164]: g = itt.groupby(sil,) Display all 465 possibilities? (y or n) In [164]: g = itt.groupby(sil, key=op.itemgetter(1)) In [165]: for k, v in g: .....: print k, list(v) .....: .....: 1 [('c', 1)] 2 [('b', 2), ('e', 2)] 3 [('a', 3), ('d', 3), ('f', 3)] In [166]: sg = sorted(g, key=lambda x: len(list(x[1]))) In [167]: sg Out[167]: []
I can always write some tedious for-loops for this, but I would rather find something more elegant. Any suggestion? If there are libraries that are useful to me, I will be happy to use them. e.g. pandas , scipy