首页 > 解决方案 > 当我将 groupby 对象转换为 dict 时,grouper 对象已用尽

问题描述

我有以下代码,它采用一个排序的元组列表,应用一个 groupby 并将其转换为 dict

from itertools import groupby
things = [("animal", "bear"), ("animal", "duck"), ("plant", "cactus"), ("vehicle", "speed boat"), ("vehicle", "school bus")]
it = groupby(things, lambda x: x[0])
dict1 = dict(it)
print(dict1)
group_animal = dict1['animal']
print(list(group_animal))

输出是

{'animal': <itertools._grouper object at 0x7ff1f370db38>, 'plant': <itertools._grouper object at 0x7ff1f370db70>, 'vehicle': <itertools._grouper object at 0x7ff1f3685128>}
[]

动物的石斑鱼对象已经用尽,即使我没有用方法循环它。为什么会这样?

标签: pythongroup-by

解决方案


您需要遍历由grouper返回的,it并且只获取second可迭代中每个值的元素。

it返回一对对象;键和 group_iterable,您只需要每个分组项目中的第二个元素。也就是说('animal', 'bear'),您只需要获取'bear',因此通过索引 like来获取item[1]

>>> from itertools import groupby
>>> things = [("animal", "bear"), ("animal", "duck"), ("plant", "cactus"), ("vehicle", "speed boat"), ("vehicle", "school bus")]
>>> it = groupby(things, lambda x: x[0])
>>> dict1 = {type_: [x[1] for x in thing] for type_,thing in it}
>>> dict1
{'animal': ['bear', 'duck'], 'plant': ['cactus'], 'vehicle': ['speed boat', 'school bus']}
>>> dict1['animal']
['bear', 'duck']

推荐阅读