react native
期望也可以是上面所有列表的列表。
答案 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]]