Python 按两列或更多列进行分组

标签 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}

最佳答案

您在第一个和中使用组迭代器,在组group = list(group)上调用list将内容存储在列表中,以便您可以使用它们两次:

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]: 

关于Python 按两列或更多列进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30355624/

相关文章:

python - 如何在Python3中获取异常详细信息

javascript - 按钮会改变颜色,即使它已经被分配

c - 如何打印这个二维数组?

php - 遍历 WordPress 帖子,并将每个 X 帖子包装在一个 DIV 中

python - 查找多次出现的值的键

python - 如何根据 Pandas 中第一个数据帧中的某些列值添加第二个数据帧中的列值

python - python 比较字符串中的字符

python - 首先获取最新的 S3 key

python - 使用计算值创建字典

python - 更改 New_dictionary 中键的名称,其中 New_dictionary 作为 Main_dictionary 的值