我想在下面的规则中压缩Python中的列表:
['a', 'a', 'a', 'b', 'b', 'c'] -> [3, 2, 1]
我想在Python中使用内置的map / reduce函数,如何制作它?
谢谢!
答案 0 :(得分:4)
>>> 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]