For Python's list comprehensions comes groupby
...
Guido inspired SQL-like GROUPBY class that also encapsulates the logic in a Unix-like "sort | uniq".
class groupby(dict):
def __init__(self, seq, key=lambda x:x):
for value in seq:
k = key(value)
self.setdefault(k, []).append(value)
__iter__ = dict.iteritems
# -------------------------- Examples -----------------------------------
>>> letters = 'abracadabra'
>>> [g for k, g in groupby(letters)] # grouped
[['a', 'a', 'a', 'a', 'a'], ['r', 'r'], ['b', 'b'], ['c'], ['d']]
>>> [k for k, g in groupby(letters)] # uniq
['a', 'r', 'b', 'c', 'd']
>>> [(k, len(g)) for k, g in groupby(letters)] # uniq -c
[('a', 5), ('r', 2), ('b', 2), ('c', 1), ('d', 1)]
>>> [k for k, g in groupby(letters) if len(g) > 1] # uniq -d
['a', 'r', 'b']
No comments:
Post a Comment