Prayag Bhatia
Prayag Bhatia

Reputation: 406

Merge similar elements of a list in one new list

I have a Python list:

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

I want to merge similar elements in a new list and put all separate lists in one other list.

For example , the output for the above input should be:

 [[1 , 1 ,1] , [2 ,2] , [3] , [4]]

Order doesn't matter.

Upvotes: 3

Views: 118

Answers (5)

Rik
Rik

Reputation: 1987

You can sort then push to an array.

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

Upvotes: 0

user12386945
user12386945

Reputation: 73

arrayA = [1 , 2 , 3 , 2 , 1 , 4 , 1]
setS = set(arrayA)
finalArray = []
for i in setS:
    tempArray = []
    for j in range(arrayA.count(i)):
        tempArray.append(i) 
    finalArray.append(tempArray)

print (finalArray)

Upvotes: 0

Mykola Zotko
Mykola Zotko

Reputation: 17794

You can use 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]]

Upvotes: 1

Austin
Austin

Reputation: 26039

Use itertools.groupby to group elements:

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]]

Upvotes: 1

Thierry Lathuille
Thierry Lathuille

Reputation: 24232

You can use a collections.Counter to count the values, and generate the sublists in a list comprehension:

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]]

Upvotes: 4

Related Questions