将itertools.groupby
个对象转换为列表似乎会导致奇怪的行为。我不明白为什么a = groupby(lst, is_divisible_by_four)
会向a = list(groupby(lst, is_divisible_by_four))
产生不同的结果。
>>> def is_divisible_by_four(x):
return x % 4 == 0
>>> lst = list(range(10))
>>> lst
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a = groupby(lst, is_divisible_by_four)
>>> [list(i[1]) for i in a]
[[0], [1, 2, 3], [4], [5, 6, 7], [8], [9]]
>>> a = list(groupby(lst, is_divisible_by_four))
>>> a
[(True, <itertools._grouper object at 0x00FA9C10>), (False, <itertools._grouper object at 0x00FA9DF0>), (True, <itertools._grouper object at 0x00FA9C70>), (False, <itertools._grouper object at 0x010092F0>), (True, <itertools._grouper object at 0x01009390>), (False, <itertools._grouper object at 0x01009290>)]
>>> [list(i[1]) for i in a]
[[], [9], [], [], [], []]