简体   繁体   English

Python - itertools.groupby

[英]Python - itertools.groupby

Just having trouble with itertools.groupby.只是遇到了 itertools.groupby 的问题。 Given a list of dictionaries,给定一个字典列表,

my_list = [
{'name': 'stock1', 'price': 200, 'shares': 100},
{'name': 'stock2', 'price': 1.2, 'shares': 1000},
{'name': 'stock3', 'price': 0.05, 'shares': 200000},
{'name': 'stock1', 'price': 200.2, 'shares': 50}]

From this list, I was hoping to create a dictionary, where the key is the name of the stock, and the value is a list of dictionaries of that stock, for example:从这个列表中,我希望创建一个字典,其中键是股票的名称,值是该股票的字典列表,例如:

{'stock1': [{'name': 'stock1', 'price': 200, 'shares': 100}, {'name': 'stock1', 'price': 200.2, 'shares': 50}] }

I ran this code:我运行了这段代码:

by_name = { name: list(items) for name, items in itertools.groupby(
            my_list, key=lambda x: x['name'])}

, and this is the result I got: ,这是我得到的结果:

 {'stock1': [{'name': 'stock1', 'price': 200.2, 'shares': 50}],
 'stock2': [{'name': 'stock2', 'price': 1.2, 'shares': 1000}],
 'stock3': [{'name': 'stock3', 'price': 0.05, 'shares': 200000}]}

For stock1, I'm expecting 2 items in the list but it only has the latest entry from the original my_list.对于 stock1,我期望列表中有 2 个项目,但它只有原始 my_list 中的最新条目。 Can anyone please point out where the mistake is?谁能指出错误在哪里? Thank you!谢谢!

That isn't how itertools.groupby works.这不是itertools.groupby的工作方式。 From the manual:从手册:

It generates a break or new group every time the value of the key function changes (which is why it is usually necessary to have sorted the data using the same key function)每次键 function 的值发生变化时,它都会生成一个中断或新组(这就是为什么通常需要使用相同的键函数对数据进行排序的原因)

So to achieve the type of grouping you want, you need to sort my_list first:所以要实现你想要的分组类型,需要先对my_list进行排序:

import itertools

my_list = [
{'name': 'stock1', 'price': 200, 'shares': 100},
{'name': 'stock2', 'price': 1.2, 'shares': 1000},
{'name': 'stock3', 'price': 0.05, 'shares': 200000},
{'name': 'stock1', 'price': 200.2, 'shares': 50}
]

my_list.sort(key=lambda x:x['name'])

by_name = { name: list(items) for name, items in itertools.groupby(
            my_list, key=lambda x: x['name'])}

print(by_name)

Output Output

{'stock1': [{'name': 'stock1', 'price': 200, 'shares': 100},
            {'name': 'stock1', 'price': 200.2, 'shares': 50}],
 'stock2': [{'name': 'stock2', 'price': 1.2, 'shares': 1000}],
 'stock3': [{'name': 'stock3', 'price': 0.05, 'shares': 200000}]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM