0

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!

4

1 回答 1

4

使用itertools.groupby

>>> 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]
于 2013-10-09T07:42:45.863 回答