尽早实现groupby结果时,Python中itertools.groupby的怪异之处 [英] Weirdness of itertools.groupby in Python when realizing the groupby result early

查看:156
本文介绍了尽早实现groupby结果时,Python中itertools.groupby的怪异之处的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,对我对该问题的描述不充分表示歉意.我找不到更好的了.

First, apologies for my poor description of the problem. I can't find a better one.

我发现将列表应用于itertools.groupby结果将破坏结果.查看代码:

I found that applying list to an itertools.groupby result will destroy the result. See code:

import itertools
import operator

log = '''\
hello world
hello there
hi guys
hi girls'''.split('\n')

data = [line.split() for line in log]

grouped = list(itertools.groupby(data, operator.itemgetter(0)))

for key, group in grouped:
    print key, group, list(group)

print '-'*80

grouped = itertools.groupby(data, operator.itemgetter(0))

for key, group in grouped:
    print key, group, list(group)

结果是:

hello <itertools._grouper object at 0x01A86050> []
hi <itertools._grouper object at 0x01A86070> [['hi', 'girls']]
--------------------------------------------------------------------------------
<itertools.groupby object at 0x01A824E0>
hello <itertools._grouper object at 0x01A860B0> [['hello', 'world'], ['hello', 'there']]
hi <itertools._grouper object at 0x01A7DFF0> [['hi', 'guys'], ['hi', 'girls']]

这可能与groupby函数的内部工作有关.尽管如此,今天却让我感到惊讶.

Probably this is related to the internal working of the groupby function. Nevertheless it surprised me today.

推荐答案

这是

返回的组本身就是一个迭代器,与groupby()共享底层的可迭代对象.因为源是共享的,所以当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.

执行list(groupby(...))时,将groupby对象一直推进到最后,这将丢失除最后一个组以外的所有组.如果需要保存组,请按照文档中所示进行操作,并在遍历groupby对象时保存每个组.

When you do list(groupby(...)), you advance the groupby object all the way to the end, this losing all groups except the last. If you need to save the groups, do as shown in the documentation and save each one while iterating over the groupby object.

这篇关于尽早实现groupby结果时,Python中itertools.groupby的怪异之处的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆