我本以为这两段代码会产生相同的结果
from itertools import groupby
for i in list(groupby('aaaabb')):
print i[0], list(i[1])
for i, j in groupby('aaaabb'):
print i, list(j)
在一种情况下,我将groupby返回的迭代器转换为一个列表并对其进行迭代,在另一种情况下,我直接对返回的迭代器进行迭代。你知道吗
此脚本的输出为
a []
b ['b']
a ['a', 'a', 'a', 'a']
b ['b', 'b']
为什么会这样?你知道吗
编辑:作为参考,groupby('aabbaa')
的结果如下
('a', <itertools._grouper object at 0x10c1324d0>)
('b', <itertools._grouper object at 0x10c132250>)
这是
groupby
函数的一个怪癖,大概是为了性能。你知道吗从^{} documentation :
所以,你可以这样做:
相关问题 更多 >
编程相关推荐