如何对列表进行分组

2024-09-24 22:28:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个列表如下:

list=[
 ('2013-01-04', u'crid2557171372', 1),
 ('2013-01-04', u'crid9904536154', 719677),
 ('2013-01-04', u'crid7990924609', 577352),
 ('2013-01-04', u'crid7990924609', 399058),
 ('2013-01-04', u'crid9904536154', 385260),
 ('2013-01-04', u'crid2557171372', 78873)
]

问题是第二列有重复id,但计数不同。我需要有一个清单,将汇总计数,使名单看起来像这样。python中是否有group by cluase?你知道吗

list=[
     ('2013-01-04', u'crid9904536154', 1104937),
     ('2013-01-04', u'crid7990924609', 976410),
     ('2013-01-04', u'crid2557171372', 78874)
    ]

Tags: id列表bygrouplist计数汇总名单
3条回答

“漫长”的道路:

>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> r = defaultdict(list)
>>> for i in l:
...    d[i[1]] += i[2]
...    r[i[0]].append(d)
... 
>>> results = []
>>> for i,v in r.iteritems():
...     for k in v[0]:
...         results.append((i,k,v[0][k]))
... 
>>> results
[('2013-01-04', u'crid9904536154', 1104937),
 ('2013-01-04', u'crid2557171372', 78874),
 ('2013-01-04', u'crid7990924609', 976410)]

让我们把你的列表命名为a,而不是listlist在Python中是一个非常有用的函数,我们不想屏蔽它):

import itertools as it

a = [('2013-01-04', u'crid2557171372', 1),
     ('2013-01-04', u'crid9904536154', 719677),
     ('2013-01-04', u'crid7990924609', 577352),
     ('2013-01-04', u'crid7990924609', 399058),
     ('2013-01-04', u'crid9904536154', 385260),
     ('2013-01-04', u'crid2557171372', 78873)]

b = []
for k,v in it.groupby(sorted(a, key=lambda x: x[:2]), key=lambda x: x[:2]):
    b.append(k + (sum(x[2] for x in v),))

b现在是:

[('2013-01-04', u'crid2557171372', 78874),
 ('2013-01-04', u'crid7990924609', 976410),
 ('2013-01-04', u'crid9904536154', 1104937)]

我不认为有任何内置的工具,可以做什么,你想在开箱即用。但是,使用collections模块中的defaultdict可以很容易地实现自己的功能:

from collections import defaultdict

counts = defaultdict(int)
for date, crid, count in lst:
    counts[(date, crid)] += count

new_lst = [(date, crid, count) for (date, crid), count in counts.items()]

这只需要线性运行时间,因此如果数据集很大,它可能比groupby实现要好,后者需要O(log n)运行时间排序。你知道吗

相关问题 更多 >