Ad

How To Find Duplicate Values In A List And Merge Them

So basically for example of you have a list like:

l = ['a','b','a','b','c','c']

The output should be:

[['a','a'],['b','b'],['c','c']]

So basically put together the values that are duplicated into a list,

I tried:

l = ['a','b','a','b','c','c']
it=iter(sorted(l))
next(it)
new_l=[]
for i in sorted(l):
   new_l.append([])
   if next(it,None)==i:
      new_l[-1].append(i)
   else:
      new_l.append([])

But doesn't work, and if it does work it is not gonna be efficient

Ad

Answer

Sort the list then use itertools.groupby:

>>> from itertools import groupby
>>> l = ['a','b','a','b','c','c']
>>> [list(g) for _, g in groupby(sorted(l))]
[['a', 'a'], ['b', 'b'], ['c', 'c']]

EDIT: this is probably not the fastest approach, sorting is O(n log n) time complexity for the average case and not required for all solutions (see the comments)

Ad
source: stackoverflow.com
Ad