Skip to main content
 首页 » 编程设计

python之您如何将列表分成原始列表中所有重复项的子列表

2025年05月04日9itcoder

l = [a, a, a, b, b, c] 
 
desired1 = [a, a, a] 
 
desired2 = [b, b] 
 
desired3 = [c] 

desired 也可以是上述所有列表的列表。

请您参考如下方法:

您可以使用 itertools.groupby()将公共(public)元素组合在一起:

>>> 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']] 
>>>  

请注意,这仅在列表已经排序后才有效,因此您可能必须在分组之前进行排序:

>>> l = ['a', 'b', 'a', 'b', 'a', 'c'] # unsorted 
>>> runs = [list(group) for _, group in groupby(sorted(l))] 
>>> runs 
[['a', 'a', 'a'], ['b', 'b'], ['c']] 
>>>