如何使用 itertools.groupby 对两次出现的数字之间的数字进行分组

How to group numbers between two occurences of a number using itertools.groupby

我有一个看起来像这样的列表 -

nums = [0,0,0,0,1,1,2,3,4,5,6,0,0,0,0,1,2,3,4,5,6,0,0,0,0]

我想获取列表中 0 之间的数字。为此,我使用了下面的代码 -

groups = list(itertools.groupby(nums, lambda item:item != 0))
groups = list(filter(lambda item:item[0], groups))
list(map(lambda item:list(item[-1]), groups))

但是我得到的输出是空列表 -

[[], []]

我想要的输出是 -

[[1,1,2,3,4,5,6], [1,2,3,4,5,6]]

如何使用 itertools.groupby 执行此操作?

尝试:

from itertools import groupby

nums = [0,0,0,0,1,1,2,3,4,5,6,0,0,0,0,1,2,3,4,5,6,0,0,0,0]

output = [list(g) for k, g in groupby(nums, lambda x: x != 0) if k]
print(output) # [[1, 1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6]]

doc

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.

所以我的客人是第一行

groups = list(itertools.groupby(nums, lambda item:item != 0))

是罪魁祸首。当 list 遍历 groupby 对象时,其中的每个组也会被消耗。您可以改为使用

groups = [(k, list(g)) for k, g in groupby(nums, lambda x: x != 0)]

存储结果。


要查看此内容:

groups = groupby(nums, lambda x: x != 0)
k1, g1 = next(groups)
print(k1, list(g1)) # False [0, 0, 0, 0]

groups = groupby(nums, lambda x: x != 0)
k1, g1 = next(groups)
k2, g2 = next(groups)
print(k1, list(g1), k2, list(g2)) # False [] True [1, 1, 2, 3, 4, 5, 6]