Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unique lists from a list

Tags:

python

Given a list I need to return a list of lists of unique items. I'm looking to see if there is a more Pythonic way than what I came up with:

def unique_lists(l):
    m = {}
    for x in l:
        m[x] = (m[x] if m.get(x) != None else []) + [x]
    return [x for x in m.values()]    

print(unique_lists([1,2,2,3,4,5,5,5,6,7,8,8,9]))

Output:

[[1], [2, 2], [3], [4], [5, 5, 5], [6], [7], [8, 8], [9]]
like image 902
Yuriy Zubarev Avatar asked Mar 30 '12 04:03

Yuriy Zubarev


2 Answers

>>> L=[1,2,2,3,4,5,5,5,6,7,8,8,9]
>>> from collections import Counter
>>> [[k]*v for k,v in Counter(L).items()]
[[1], [2, 2], [3], [4], [5, 5, 5], [6], [7], [8, 8], [9]]
like image 144
John La Rooy Avatar answered Oct 05 '22 17:10

John La Rooy


Using default dict.

>>> from collections import defaultdict
>>> b = defaultdict(list)
>>> a = [1,2,2,3,4,5,5,5,6,7,8,8,9]
>>> for x in a:
...     b[x].append(x)
...
>>> b.values()
[[1], [2, 2], [3], [4], [5, 5, 5], [6], [7], [8, 8], [9]]
like image 25
Amjith Avatar answered Oct 05 '22 18:10

Amjith