4

I have a group of items that are labeled like item_labels = [('a', 3), ('b', 2), ('c', 1), ('d', 3), ('e', 2), ('f', 3)]

I want to sort them by the size of group. e.g., label 3 has size 3 and label 2 has size 2 in the above example.

I tried using a combination of groupby and sorted but didn't 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]: [] # not exactly know why I got an empty list here

I can always write some tedious for-loop to do this, but I would rather find something more elegant. Any suggestion? If there are libraries that are useful I would happy to use that. e.g., pandas, scipy

4

5 回答 5

3

在python2.7及以上,使用Counter:

from collections import Counter
c = Counter(y for _, y in item_labels)
item_labels.sort(key=lambda t : c[t[1]])

在 python2.6 中,为了我们的目的,这个Counter构造函数可以使用defaultdict(如@perreal 所建议的那样)以这种方式实现:

from collections import defaultdict
def Counter(x):
    d = defaultdict(int)
    for v in x: d[v]+=1
    return d

由于我们只使用数字,并且假设数字与您的示例中的数字一样低,我们实际上可以使用一个列表(它将与更旧版本的 Python 兼容):

def Counter(x):
    lst = list(x)
    d = [0] * (max(lst)+1)
    for v in lst: d[v]+=1
    return d

没有计数器,你可以简单地这样做:

item_labels.sort(key=lambda t : len([x[1] for x in item_labels if x[1]==t[1] ]))

它较慢,但在短名单上是合理的。


你有一个空列表的原因是它g是一个生成器。您只能对其进行一次迭代。

于 2013-06-24T21:40:08.267 回答
3
from collections import defaultdict
import operator
l=[('c', 1), ('b', 2), ('e', 2), ('a', 3), ('d', 3), ('f', 3)]
d=defaultdict(int)
for p in l: d[p[1]] += 1
print [ p for i in sorted(d.iteritems(), key=operator.itemgetter(1))
        for p in l if p[1] == i[1] ]
于 2013-06-24T21:51:33.103 回答
2

itertools.groupby返回一个迭代器,所以这个 for 循环:for k, v in g:实际上消耗了那个迭代器。

>>> it = iter([1,2,3])
>>> for x in it:pass
>>> list(it)          #iterator already consumed by the for-loop
[]

代码:

>>> lis = [('a', 3), ('b', 2), ('c', 1), ('d', 3), ('e', 2), ('f', 3)]
>>> from operator import itemgetter
>>> from itertools import groupby
>>> lis.sort(key = itemgetter(1) )
>>> new_lis = [list(v) for k,v in groupby(lis, key = itemgetter(1) )]
>>> new_lis.sort(key = len)
>>> new_lis
[[('c', 1)], [('b', 2), ('e', 2)], [('a', 3), ('d', 3), ('f', 3)]]

要获得扁平列表,请使用itertools.chain

>>> from itertools import chain
>>> list( chain.from_iterable(new_lis))
[('c', 1), ('b', 2), ('e', 2), ('a', 3), ('d', 3), ('f', 3)]
于 2013-06-24T21:38:59.300 回答
2

@perreal和@Elazar答案相同,但名称更好:

from collections import defaultdict

size = defaultdict(int)
for _, group_id in item_labels:
   size[group_id] += 1

item_labels.sort(key=lambda (_, group_id): size[group_id])
print item_labels
# -> [('c', 1), ('b', 2), ('e', 2), ('a', 3), ('d', 3), ('f', 3)]
于 2013-06-24T22:16:48.347 回答
1

这是另一种方式:

example=[('a', 3), ('b', 2), ('c', 1), ('d', 3), ('e', 2), ('f', 3)]

out={}
for t in example:
    out.setdefault(t[1],[]).append(t)

print sorted(out.values(),key=len)

印刷:

[[('c', 1)], [('b', 2), ('e', 2)], [('a', 3), ('d', 3), ('f', 3)]]

如果你想要一个平面列表:

print [l for s in sorted(out.values(),key=len) for l in s]
[('c', 1), ('b', 2), ('e', 2), ('a', 3), ('d', 3), ('f', 3)]
于 2013-06-24T22:25:56.193 回答