Luke
Luke

Reputation: 553

How would you separate a list into sublists of all the duplicates in the original?

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

desired1 = [a, a, a]

desired2 = [b, b]

desired3 = [c]

desired could also be a list of all the lists above.

Upvotes: 1

Views: 166

Answers (4)

Yoav Glazner
Yoav Glazner

Reputation: 8066

Another option using Counter :)

from collections import Counter
l = ['a', 'a', 'a', 'b', 'b', 'c']
c = Counter(l)
result = [ [k]*v for k, v in c.items() ]

Upvotes: 2

Pedro
Pedro

Reputation: 409

Slightly more straightforward dict approach

>>> l = [1,2,1,3,4,2,3,1,1,4]
>>> out = {}
>>> for i in set(l):
         out[i] = []
...
>>> for i in l:
...      out[i].append(i)
>>> out
{1: [1, 1, 1, 1], 2: [2, 2], 3: [3, 3], 4: [4, 4]}
>>> out.values()
[[1, 1, 1, 1], [2, 2], [3, 3], [4, 4]]

Upvotes: 1

PYA
PYA

Reputation: 8636

an easy way is to use a dict

dict = {}
for thing in list:
  dict[thing] += 1

list = []
for key in dict:
  curr_list = [] 
  for i in range(dict[key]):
    curr_list.append(key)
  list.append(curr_list)

Upvotes: 1

Chris
Chris

Reputation: 22953

You can use itertools.groupby() to group common elements together:

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

Note this will only work if the list has already been sorted, so you may have to sort before grouping:

>>> l = ['a', 'b', 'a', 'b', 'a', 'c'] # unsorted
>>> runs = [list(group) for _, group in groupby(sorted(l))]
>>> runs
[['a', 'a', 'a'], ['b', 'b'], ['c']]
>>>

Upvotes: 6

Related Questions