问题
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