I want to compress a list in Python in the rule below:
['a', 'a', 'a', 'b', 'b', 'c'] -> [3, 2, 1]
I want to use the built-in map/reduce function in Python, how to make it?
Thanks!
I want to compress a list in Python in the rule below:
['a', 'a', 'a', 'b', 'b', 'c'] -> [3, 2, 1]
I want to use the built-in map/reduce function in Python, how to make it?
Thanks!
>>> import itertools
>>> [len(list(grp)) for key, grp in itertools.groupby(['a', 'a', 'a', 'b', 'b', 'c'])]
[3, 2, 1]
>>> [sum(1 for _ in grp) for key, grp in itertools.groupby(['a', 'a', 'a', 'b', 'b', 'c'])]
[3, 2, 1]
使用map
, reduce
:
>>> import operator
>>>
>>> def f(result, item):
... if result and result[-1][0] == item:
... return result[:-1] + [[item, result[-1][1]+1]]
... else:
... return result + [[item, 1]]
...
>>> map(operator.itemgetter(1), reduce(f, ['a', 'a', 'a', 'b', 'b', 'c'], []))
[3, 2, 1]