我有以下清单:
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
谢谢。你知道吗
在这里使用^{} 会更有效:
输出:
也许是这个?你知道吗
相关问题 更多 >
编程相关推荐