itertools groupby对象未正确输出

2024-04-19 05:15:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用itertools.groupby为了帮助我按正或负属性对整数列表进行分组,例如:

输入

[1,2,3, -1,-2,-3, 1,2,3, -1,-2,-3] 

会回来的

^{pr2}$

但是,如果我:

import itertools

nums = [1,2,3, -1,-2,-3, 1,2,3, -1,-2,-3]
group_list = list(itertools.groupby(nums, key=lambda x: x>=0))
print(group_list)
for k, v in group_list:
    print(list(v))
>>>
[]
[-3]
[]
[]

但是如果我不list()groupby对象,它会很好地工作:

nums = [1,2,3, -1,-2,-3, 1,2,3, -1,-2,-3]
group_list = itertools.groupby(nums, key=lambda x: x>=0)
for k, v in group_list:
    print(list(v))
>>>
[1, 2, 3]
[-1, -2, -3]
[1, 2, 3]
[-1, -2, -3]

我不明白的是,groupby对象是由一对键和_grouper对象组成的迭代器,对groupby对象的list()的调用不应该使用_grouper对象?

即使它消耗了,我如何从第二个元素得到[-3]


Tags: 对象lambdakeyin列表for属性group
1条回答
网友
1楼 · 发布于 2024-04-19 05:15:33

根据the docs,需要明确指出的是,推进groupby对象会使前一个组不可用(实际上,为空):

The returned group is itself an iterator that shares the underlying iterable with groupby(). Because the source is shared, when the groupby() object is advanced, the previous group is no longer visible. So, if that data is needed later, it should be stored as a list.

基本上,在推进groupby对象之前,您需要一个listcomp从组迭代器转换为lists,而不是直接使用list构造函数进行验证,替换:

group_list = list(itertools.groupby(nums, key=lambda x: x>=0))

有:

^{pr2}$

大多数itertools模块类型的设计都是为了避免隐式存储数据,因为它们用于潜在的巨大输入。如果所有的分组程序都存储了来自输入的所有数据的副本(并且groupby对象必须确保能够反向填充它们),那么它将变得丑陋,并可能意外地破坏内存。根据Python的Zen,通过强制将值存储为显式,您不会意外地意外地存储无限量的数据:

Explicit is better than implicit.

相关问题 更多 >