Python 将列表中的类似元素合并到一个新列表中

Python 将列表中的类似元素合并到一个新列表中,python,python-3.x,Python,Python 3.x,我有一个Python列表: A = [1 , 2 , 3 , 2 , 1 , 4 , 1] 我想将相似的元素合并到一个新列表中,并将所有单独的列表放在另一个列表中 例如,上述输入的输出应为: [[1 , 1 ,1] , [2 ,2] , [3] , [4]] 秩序不重要 您可以使用计算值,并在列表中生成子列表: from collections import Counter A = [1 , 2 , 3 , 2 , 1 , 4 , 1] out = [[item]*count for

我有一个Python列表:

A = [1 , 2 , 3 , 2 , 1 , 4 , 1]
我想将相似的元素合并到一个新列表中,并将所有单独的列表放在另一个列表中

例如,上述输入的输出应为:

 [[1 , 1 ,1] , [2 ,2] , [3] , [4]]
秩序不重要

您可以使用计算值,并在列表中生成子列表:

from collections import Counter

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

out = [[item]*count for item, count in Counter(A).items()]
print(out)
# [[1, 1, 1], [2, 2], [3], [4]]

使用
itertools.groupby
对元素进行分组:

from itertools import groupby

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

print([list(g) for _, g in groupby(sorted(A))])
# [[1, 1, 1], [2, 2], [3], [4]]

您可以使用
defaultdict

from collections import defaultdict

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

dct = defaultdict(list)
for i in lst:
    dct[i].append(i)

print(list(dct.values()))
# [[1, 1, 1], [2, 2], [3], [4]]

您可以排序,然后推送到数组

A.sort()
ans = [[]]
for num in A:
    if ans[-1] and ans[-1][-1] == num:
        ans[-1] += [num]
    else:
        ans += [[num]]
print(ans)

很好的解决方案。值得一提的是,这是一个O(n)解决方案,而预排序(替代方案)是O(n log n)。
A.sort()
ans = [[]]
for num in A:
    if ans[-1] and ans[-1][-1] == num:
        ans[-1] += [num]
    else:
        ans += [[num]]
print(ans)