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]]
>>> 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]]
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]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With