python groupby and list interaction

拜拜、爱过 提交于 2020-01-30 11:47:47

问题


If we run the following code,

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)

then surprisingly the two output lines are DIFFERENT:

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

But if we remove the line "x=list(r)", then the two lines are the same, as expected. I don't understand why the list() function will change the groupby result.


回答1:


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.



来源:https://stackoverflow.com/questions/57446910/python-groupby-and-list-interaction

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!