Yuriy Zubarev
Yuriy Zubarev

Reputation: 2871

Unique lists from a list

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

Upvotes: 7

Views: 451

Answers (3)

Bastiaan
Bastiaan

Reputation: 4672

I find the build in function set() useful very often:

lst=[1,2,2,3,4,5,5,5,6,7,8,8,9]

def all_eq_elms(lst, elm):
    while True:
        try:
            yield lst.pop(lst.index(elm))
        except:
            break

[[e for e in all_eq_elms(lst,elm)] for elm in set(lst)]

Out[43]: [[1], [2, 2], [3], [4], [5, 5, 5], [6], [7], [8, 8], [9]]

Upvotes: 0

John La Rooy
John La Rooy

Reputation: 304167

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

Upvotes: 9

Amjith
Amjith

Reputation: 23814

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

Upvotes: 2

Related Questions