遍历生成器和转换为lis之间的区别

2024-10-03 06:28:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我本以为这两段代码会产生相同的结果

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>)

Tags: 代码infromimport列表forobject情况
1条回答
网友
1楼 · 发布于 2024-10-03 06:28:05

这是groupby函数的一个怪癖,大概是为了性能。你知道吗

^{} documentation

The returned group is itself an iterator that shares the underlying iterable with groupby(). Because the source is shared, when the groupby() object is advanced, the previous group is no longer visible. So, if that data is needed later, it should be stored as a list:

groups = []
uniquekeys = []
data = sorted(data, key=keyfunc)
for k, g in groupby(data, keyfunc):
    groups.append(list(g))      # Store group iterator as a list
    uniquekeys.append(k)

所以,你可以这样做:

for i in [x, list(y) for x, y in groupby('aabbaa')]:
    print i[0], i[1]

相关问题 更多 >