Python 3.3中itertools.groupby的奇怪行为

时间:2014-02-20 14:57:16

标签: python python-3.x itertools

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], [], [], [], []]

0 个答案:

没有答案