3 回答

TA貢獻(xiàn)1840條經(jīng)驗(yàn) 獲得超5個(gè)贊
試試這個(gè)
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]

TA貢獻(xiàn)1872條經(jīng)驗(yàn) 獲得超4個(gè)贊
最好的方法是一個(gè)O(n)解決方案collections.defaultdict:
>>> l = [2, 3, 7, 2, 3, 8, 7, 3]
>>> d = defaultdict(list)
>>> for e in l:
... d[e].append(e)
...
>>> d
defaultdict(<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]]
正如我發(fā)布的那樣,defaultdict 解決方案O(n)比其他方法更快。以下是測(cè)試:
from timeit import timeit
setup = (
"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))
結(jié)果:
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
這是現(xiàn)場(chǎng)測(cè)試

TA貢獻(xiàn)1773條經(jīng)驗(yàn) 獲得超3個(gè)贊
這是使用的一種簡(jiǎn)短方法 Counter
from collections import Counter
my_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]]
添加回答
舉報(bào)