Yuriy Zubarev Yuriy Zubarev - 28 days ago 16
Python Question

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

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