Why can the same label form two itertools groups?
groupby starts a new group when the key changes, so each group represents a contiguous run.
Python example and interpretation
Labels A,A,B,A form three runs. Preserve order to analyze streaks, but combine across runs when measuring overall class frequency.
from itertools import groupby
[(k,len(list(g))) for k,g in groupby('AABA')]Result [('A', 2), ('B', 1), ('A', 1)]
中文
为什么相同标签在 groupby 结果里出现两次?
groupby 在键变化时启动新组,聚合的是连续片段。
Python 算例与适用条件
标注顺序 A、A、B、A 包含三个连续段。分析运行段时应保留顺序;统计全局类别频数时要跨段合并。
from itertools import groupby
[(k,len(list(g))) for k,g in groupby('AABA')]结果 [('A', 2), ('B', 1), ('A', 1)]