Python groupby由两列或更多列组成

时间:2015-05-20 16:39:33

标签: python loops dictionary group-by

有人可以解释我为什么我不能得到第二个索引(传入)的总和。我试图在第一次迭代之后打印变量 group 的值,似乎迭代后没有更多的值。

我从这个例子中获取了一些代码。 example post

products = {}
products['product']= [ {
                    'id':1234,
                    'stock_id':1001,
                    'lot_id':5001,
                    'name':'product1',
                    'qty':50,
                    'incoming':100,
                }
                .................
                .................
           ]

grouper = itemgetter("id","stock_id","lot_id")
result = []

for key, group in groupby(sorted(products['product'], key= grouper),grouper):    
temp_dict= dict(zip(["id","stock_id","lot_id"], key))
temp_dict["qty"] = sum(item["qty"] for item in group)
temp_dict["incoming"]  = sum(item["incoming"] for item in group)

result.append(temp_dict)



for r in result:
  print r

结果

{'lot_id': 5001, 'stock_id': 1001, 'incoming': 0, 'id': 1234, 'qty': 250}
{'lot_id': 5001, 'stock_id': 1001, 'incoming': 0, 'id': 1235, 'qty': 50}
{'lot_id': 5002, 'stock_id': 1001, 'incoming': 0, 'id': 1235, 'qty': 100}
{'lot_id': 5001, 'stock_id': 1002, 'incoming': 0, 'id': 1236, 'qty': 100}

1 个答案:

答案 0 :(得分:2)

您在组for key, group in groupby(sorted(products['product'], key=grouper), grouper): temp_dict = dict(zip(["id", "stock_id", "lot_id"], key)) group = list(group) temp_dict["qty"] = sum(item["qty"] for item in group) temp_dict["incoming"] = sum(item["incoming"] for item in group) 的第一个总和,呼叫列表中使用组迭代器,以将内容存储在列表中,以便您可以使用它们两次:

In [4]: group = iter([1,2,3,4])

In [5]: for ele in group: # iterator will be consumed
           print(ele)
   ...:     
1
2
3
4

In [6]: for ele in group: # nothing left to iterate
           print(ele)
   ...:     

In [7]: 

你基本上是这样做的:

app.config(function($provide){
    $provide.decorator('uiGridGroupingService', function ($delegate,i18nService,gridUtil) {

        $delegate.groupingColumnBuilder = function (colDef, col, gridOptions) {

          if (colDef.enableGrouping === false){
            return;
          }

          if ( typeof(col.grouping) === 'undefined' && typeof(colDef.grouping) !== 'undefined') {
            col.grouping = angular.copy(colDef.grouping);
          } else if (typeof(col.grouping) === 'undefined'){
            col.grouping = {};
          }

          if (typeof(col.grouping) !== 'undefined' && typeof(col.grouping.groupPriority) !== undefined && col.grouping.groupPriority >= 0){
            col.suppressRemoveSort = true;
          } 

          col.groupingSuppressAggregationText = colDef.groupingSuppressAggregationText === true;

          var groupColumn = {
            name: 'ui.grid.grouping.group',
            title: i18nService.get().grouping.group,
            icon: 'ui-grid-icon-indent-right',
            shown: function () {
              return typeof(this.context.col.grouping) === 'undefined' || 
                     typeof(this.context.col.grouping.groupPriority) === 'undefined' ||
                     this.context.col.grouping.groupPriority < 0;
            },
            action: function () {
              service.groupColumn( this.context.col.grid, this.context.col );
            }
          };

          var ungroupColumn = {
            name: 'ui.grid.grouping.ungroup',
            title: i18nService.get().grouping.ungroup,
            icon: 'ui-grid-icon-indent-left',
            shown: function () {
              return typeof(this.context.col.grouping) !== 'undefined' && 
                     typeof(this.context.col.grouping.groupPriority) !== 'undefined' &&
                     this.context.col.grouping.groupPriority >= 0;
            },
            action: function () {
              service.ungroupColumn( this.context.col.grid, this.context.col );
            }
          };



          if (!gridUtil.arrayContainsObjectWithProperty(col.menuItems, 'name', 'ui.grid.grouping.group')) {
            col.menuItems.push(groupColumn);
          }

          if (!gridUtil.arrayContainsObjectWithProperty(col.menuItems, 'name', 'ui.grid.grouping.ungroup')) {
            col.menuItems.push(ungroupColumn);
          }
        }
        return $delegate;
    })
});