Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用itertools.groupby汇总报告_Python_Python 3.x - Fatal编程技术网

Python 使用itertools.groupby汇总报告

Python 使用itertools.groupby汇总报告,python,python-3.x,Python,Python 3.x,有人能帮我按函数第一列、第二列和第三列分组吗 from itertools import groupby from operator import itemgetter things = [('2009-09-02','j', 12), ('2009-09-02','j', 3), ('2009-09-03','k',10), ('2009-09-03','k',4), ('2009-09-03','u', 22)

有人能帮我按函数第一列、第二列和第三列分组吗

from itertools import groupby
from operator import itemgetter

things = [('2009-09-02','j', 12),
          ('2009-09-02','j', 3),
          ('2009-09-03','k',10),
          ('2009-09-03','k',4),
          ('2009-09-03','u', 22),
          ('2009-09-06','m',33)]

for k, items in groupby(things, itemgetter(1)):    
    for subitem in items:
        print(subitem)
得到这个结果:

('2009-09-02', 'j', 12) ('2009-09-02', 'j', 3) ('2009-09-03', 'k', 10) ('2009-09-03', 'k', 4) ('2009-09-03', 'u', 22) ('2009-09-06', 'm', 33) 
 ('2009-09-02', 'j', 15) ('2009-09-03', 'k', 14) ('2009-09-03', 'u', 22) ('2009-09-06', 'm', 33)
期待这一结果:

('2009-09-02', 'j', 12) ('2009-09-02', 'j', 3) ('2009-09-03', 'k', 10) ('2009-09-03', 'k', 4) ('2009-09-03', 'u', 22) ('2009-09-06', 'm', 33) 
 ('2009-09-02', 'j', 15) ('2009-09-03', 'k', 14) ('2009-09-03', 'u', 22) ('2009-09-06', 'm', 33)
========================================================================

   sales = [('Scotland', 'Edinburgh', 20000),
         ('Scotland', 'Glasgow', 12500),
         ('Wales', 'Cardiff', 29700),
         ('Wales', 'Bangor', 12800),
         ('England', 'London', 90000),
         ('England', 'Manchester', 45600),
         ('England', 'London', 29700)]
您不需要groupby作为一种更有效的方法,您可以将dictionary与dict.setdefault方法结合使用:

如果您想使用groupby作为提示,您可能会注意到需要将索引传递给itemgetter函数:

itemgetter(0, 1)
如果你想求和,你必须求和,简单地打印它不会神奇地为你求和

另外,根据您的示例,您似乎应该基于第一列和第二列进行分组。范例-

for k,items in groupby(things, itemgetter(0, 1)):    
    print(k + (sum(x[2] for x in items),)

谢谢你,莎伦。我在上面的销售示例中又添加了一个。然而,出于某种原因,它不会总结英格兰和伦敦?