l = [a, a, a, b, b, c]
desired1 = [a, a, a]
desired2 = [b, b]
desired3 = [c]
Run Code Online (Sandbox Code Playgroud)
期望也可以是上面所有列表的列表.
您可以使用itertools.groupby()将常见元素组合在一起:
>>> from itertools import groupby
>>> l = ['a', 'a', 'a', 'b', 'b', 'c']
>>>
>>> runs = [list(group) for _, group in groupby(l)]
>>> runs
[['a', 'a', 'a'], ['b', 'b'], ['c']]
>>>
Run Code Online (Sandbox Code Playgroud)
请注意,这仅在列表已排序时才有效,因此您可能必须在分组前进行排序:
>>> l = ['a', 'b', 'a', 'b', 'a', 'c'] # unsorted
>>> runs = [list(group) for _, group in groupby(sorted(l))]
>>> runs
[['a', 'a', 'a'], ['b', 'b'], ['c']]
>>>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
75 次 |
| 最近记录: |