python 上的重复列表

list of duplicates on python

如果我有一个列表,我如何从中创建一个包含重复列表的列表? 例如,如果我有列表

L = [1,2,1,3,4,2,1,4]

我希望输出为

L1 = [[1,1,1], [2,2], [3], [4,4]]

一定有大约一百种方法可以做到这一点。这是一个。如果您想要更多,因为这确实是一个 Python 问题,请将 Python 标签添加到您的问题中。

>>> L = [1,2,1,3,4,2,1,4]
>>> from collections import Counter
>>> counts = Counter(L)
>>> counts
Counter({1: 3, 2: 2, 4: 2, 3: 1})
>>> L1 = [ [ _ ]*counts[_] for _ in counts.keys() ]
>>> L1
[[1, 1, 1], [2, 2], [3], [4, 4]]

@Bill_Bell 答案的变体。

>>> L = [1, 2, 1, 3, 4, 2, 1, 4]
>>> from collections import Counter
>>> counts = Counter(L)
>>> counts
Counter({1: 3, 2: 2, 4: 2, 3: 1})
>>> L2 = [[a]*b for (a,b) in counts.items()]
>>> L2
[[1, 1, 1], [2, 2], [3], [4, 4]]

作为 collections.Counter 答案的替代方法,您可以使用 itertools.groupby:

import itertools

L = [1,2,1,3,4,2,1,4]
grouped = [list(group) for key, group in itertools.groupby(sorted(L))]
print(grouped) # -> [[1, 1, 1], [2, 2], [3], [4, 4]]