Python - itertools.groupby

Python - itertools.groupby

只是遇到了 itertools.groupby 的问题。给定一个字典列表,

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

根据这个列表,我希望创建一个字典,其中键是股票的名称,值是该股票的字典列表,例如:

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

我运行这个代码:

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

,这是我得到的结果:

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

对于 stock1,我希望列表中有 2 个项目,但它只有原始 my_list 中的最新条目。谁能指出错误在哪里?谢谢!

那不是 itertools.groupby 的工作方式。来自手册:

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)

所以要实现你想要的分组类型,需要先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)

输出

{'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}]
}