如何使用groupby对列表中的元素进行分组和筛选?

2024-09-29 02:15:52 发布

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

我有以下清单:

itemlist=[('ItemA', '0', 'Type1'), ('ItemA', '0', 'Type2'),('ItemA', '0', 'Type1'), ('ItemB', '0', 'Type2'), ('ItemA', '1', 'Type2'), ('ItemB', '2', 'Type1'), ('ItemB', '1', 'Type3'), ('ItemB', '1', 'Type1'), ('ItemC', '1', 'Type4'), ('ItemD', '1', 'Type4')]

接下来,我按数字对项目进行分组,并计算数字:

from itertools import groupby

sortkeyfn_num = key = lambda s:s[0]
itemlist.sort(key=sortkeyfn_num)

result_name_dict = {}
for key,valuesiter in groupby(itemlist, key=sortkeyfn_num):
    result_name_dict[key] = tuple(v[1] for v in valuesiter)

res = {}
for k in result_name_dict.keys():
for i in result_name_dict.values()[result_name_dict.keys().index(k)]:
    res.setdefault(i, 0)
    res[i] += 1
print k,'=', res
res.clear()

结果:

ItemB = {'1': 2, '0': 1, '2': 1}
ItemC = {'1': 1}
ItemA = {'1': 1, '0': 3}
ItemD = {'1': 1}

但如何按数字和类型对项目进行分组,并在结果中计算类型呢? 结果必须是,例如:

ItemA 0: Type1 = 2
ItemA 0: Type2 = 1
ItemA 1: Type2 = 1
ItemB 0: Type2 = 1
ItemB 1: Type3 = 2

谢谢。你知道吗


Tags: keynameinforres数字resultnum
2条回答

在这里使用^{}会更有效:

from collections import Counter
itemlist=[('ItemA', '0', 'Type1'), ('ItemA', '0', 'Type2'),('ItemA', '0', 'Type1'), ('ItemB', '0', 'Type2'), ('ItemA', '1', 'Type2'), ('ItemB', '2', 'Type1'), ('ItemB', '1', 'Type3'), ('ItemB', '1', 'Type1'), ('ItemC', '1', 'Type4'), ('ItemD', '1', 'Type4')]
for (a,b,c),d in sorted(Counter(itemlist).items()):
    print "{} {}: {} = {}".format(a, b, c, d)

输出:

ItemA 0: Type1 = 2
ItemA 0: Type2 = 1
ItemA 1: Type2 = 1
ItemB 0: Type2 = 1
ItemB 1: Type1 = 1
ItemB 1: Type3 = 1
ItemB 2: Type1 = 1
ItemC 1: Type4 = 1
ItemD 1: Type4 = 1

也许是这个?你知道吗

import collections
itemlist = [('ItemA', '0', 'Type1'), ('ItemA', '0', 'Type2'),('ItemA', '0', 'Type1'), ('ItemB', '0', 'Type2'), ('ItemA', '1', 'Type2'), ('ItemB', '2', 'Type1'), ('ItemB', '1', 'Type3'), ('ItemB', '1', 'Type1'), ('ItemC', '1', 'Type4'), ('ItemD', '1', 'Type4')]
data_dict = collections.defaultdict(int)
for attribute1, attribute2, attribute3 in itemlist:
    data_dict[(attribute1, attribute2, attribute3)] += 1
for key, value in sorted(data_dict.items()):
    attribute1, attribute2, attribute3 = key
    print("{attribute1} {attribute2}: {attribute3} = {value}".format(**locals()))

相关问题 更多 >