繁体   English   中英

如何使用map或reduce函数在Python中压缩列表?

[英]How can I compress a list in Python using map or reduce function?

我想按照以下规则在Python中压缩列表:

['a', 'a', 'a', 'b', 'b', 'c']  ->  [3, 2, 1]

我想在Python中使用内置的map / reduce函数,如何制作?

谢谢!

使用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]

使用mapreduce

>>> 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]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM