python - 当我将 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>}
[]
动物的石斑鱼对象已经用尽,即使我没有用方法循环它。为什么会这样?
解决方案
您需要遍历由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']
推荐阅读
- sql - 选择总和不为零的行
- java - 尝试将在模拟器上运行的 Android 应用程序连接到在 localhost 中运行的 Servlet
- c# - 在 OnGet 和 OnPost 之间保持对象状态
- node.js - ValidatorJS isNumeric 函数无法正常工作
- angular - Angular 9 - 导航开始时获取目标网址
- wand - 如何将所有颜色更改为透明但只有一种?
- docker - Dockerfile ADD - 嵌入图像或添加到容器中?
- c# - 可以在 localhost 中访问私有文件,但不能在生产环境中访问
- c - 如何解决泛型函数中的 E0852“表达式必须是指向完整对象类型的指针”
- entity-framework - 具有“NULL”值的 EF Core 唯一约束