扫码关注官方订阅号
a = [1, 1, 2, 2, 2, 3] 元素已排好序 希望变成: b = [2, 4, 5] 即按照出现次数累加 怎么写比较简洁高效?
pythonimport collections counter = collections.Counter([1, 1, 2, 2, 2, 3]) print counter >>> Counter({2: 3, 1: 2, 3: 1})
python
import collections counter = collections.Counter([1, 1, 2, 2, 2, 3]) print counter >>> Counter({2: 3, 1: 2, 3: 1})
>>> valdict = dict((k, len(list(g))) for k, g in groupby(sorted(a))) >>> >>> for key, val in valdict.items(): print key, ":", val ... 1 : 2 2 : 3 3 : 1
微信扫码关注PHP中文网服务号
QQ扫码加入技术交流群
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP学习
技术支持
返回顶部