尽早实现groupby结果时,Python中itertools.groupby的怪异之处 [英] Weirdness of itertools.groupby in Python when realizing the groupby result early
本文介绍了尽早实现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.
推荐答案
查看全文