首页 > 解决方案 > python groupby和list交互

问题描述

如果我们运行以下代码,

from itertools import groupby
    s = '1223'
    r = groupby(s)
    x = list(r)
    a = [list(g) for k, g in r]
    print(a)
    b =[list(g) for k, g in groupby(s)]
    print(b)

然后令人惊讶的是,两条输出线是不同的:

[]
[['1'], ['2', '2'], ['3']]

但是如果我们删除行“x=list(r)”,那么这两行是相同的,正如预期的那样。我不明白为什么 list() 函数会改变 groupby 结果。

标签: pythonlistgroup-by

解决方案


The result of groupby, as with many objects in the itertools library, is an iterable that can only be iterated over once. This is to allow lazy evaluation. Therefore, when you call something like list(r), r is now an empty iterable.

When you iterate over the empty iterable, of course the resulting list is empty. In your second case, you don't consume the iterable before you iterate over it. Thus, the iterable is not empty.


推荐阅读