0
我想在下面的規則來壓縮在Python列表:如何使用map或reduce函數在Python中壓縮列表?
['a', 'a', 'a', 'b', 'b', 'c'] -> [3, 2, 1]
我想使用內置的map/reduce Python函數中,如何做的?
謝謝!
我想在下面的規則來壓縮在Python列表:如何使用map或reduce函數在Python中壓縮列表?
['a', 'a', 'a', 'b', 'b', 'c'] -> [3, 2, 1]
我想使用內置的map/reduce Python函數中,如何做的?
謝謝!
>>> 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]