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

时间:2017-07-05 20:10:05

标签: python python-3.x

react native

期望也可以是上面所有列表的列表。

4 个答案:

答案 0 :(得分:6)

您可以使用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']]
>>> 

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

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

答案 1 :(得分:2)

使用计数器:)

的另一个选项
from collections import Counter
l = ['a', 'a', 'a', 'b', 'b', 'c']
c = Counter(l)
result = [ [k]*v for k, v in c.items() ]

答案 2 :(得分:1)

一种简单的方法是使用dict

dict = {}
for thing in list:
  dict[thing] += 1

list = []
for key in dict:
  curr_list = [] 
  for i in range(dict[key]):
    curr_list.append(key)
  list.append(curr_list)

答案 3 :(得分:1)

稍微简单dict方法

>>> l = [1,2,1,3,4,2,3,1,1,4]
>>> out = {}
>>> for i in set(l):
         out[i] = []
...
>>> for i in l:
...      out[i].append(i)
>>> out
{1: [1, 1, 1, 1], 2: [2, 2], 3: [3, 3], 4: [4, 4]}
>>> out.values()
[[1, 1, 1, 1], [2, 2], [3, 3], [4, 4]]