慕斯709654
试试这个l = [2, 3, 7, 2, 3, 8, 7, 3]for i in set(l): print([i]*l.count(i))输出:[8][2, 2][3, 3, 3][7, 7]
守着一只汪
最好的方法是一个O(n)解决方案collections.defaultdict:>>> l = [2, 3, 7, 2, 3, 8, 7, 3]>>> d = defaultdict(list)>>> for e in l:... d[e].append(e)... >>> ddefaultdict(<class 'list'>, {2: [2, 2], 3: [3, 3, 3], 7: [7, 7], 8: [8]})>>> d.values()dict_values([[2, 2], [3, 3, 3], [7, 7], [8]])或者,您可以使用itertools.groupby排序列表:>>> for _, l in itertools.groupby(sorted(l)):... print(list(l))... [2, 2][3, 3, 3][7, 7][8]或列表理解collections.Counter:>>> from collections import Counter>>> [[i]*n for i,n in Counter(l).items()][[2, 2], [3, 3, 3], [7, 7], [8]]正如我发布的那样,defaultdict 解决方案O(n)比其他方法更快。以下是测试:from timeit import timeitsetup = ("from collections import Counter, defaultdict;""from itertools import groupby;""l = [2, 3, 7, 2, 3, 8, 7, 3];")defaultdict_call = ("d = defaultdict(list); ""\nfor e in l: d[e].append(e);")groupby_call = "[list(g) for _,g in groupby(sorted(l))]"counter_call = "[[i]*n for i,n in Counter(l).items()]"for call in (defaultdict_call, groupby_call, counter_call): print(call) print(timeit(call, setup))结果:d = defaultdict(list); for e in l: d[e].append(e);7.02662614302244[list(g) for _,g in groupby(sorted(l))]10.126392606005538[[i]*n for i,n in Counter(l).items()]19.55539561196929这是现场测试
慕容3067478
这是使用的一种简短方法 Counterfrom collections import Countermy_dict = Counter([2, 3, 7, 2, 3, 8, 7, 3]) # returns {3: 3, 2: 2, 7: 2, 8: 1}new_list = [[k] * v for k,v in my_dict.items()] 输出:[[2, 2], [3, 3, 3], [7, 7], [8]]