V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
going
V2EX  ›  Python

Python 列表的相邻正负数合并有啥好方法嘛?

  •  
  •   going · 2021-03-02 16:11:05 +08:00 · 1275 次点击
    这是一个创建于 1144 天前的主题,其中的信息可能已经有所发展或是发生改变。

    请问 Python 列表的相邻正负数合并有啥好方法嘛?

    比如 meta = [0.24, -0.6, -0.68, 0.73, 0.34] 这个列表需要改为 meta = [0.24, -1.28, 1.07]

    3 条回复    2021-03-02 17:02:49 +08:00
    013231
        1
    013231  
       2021-03-02 16:30:02 +08:00   ❤️ 7
    from itertools import groupby

    meta = [sum(g) for _, g in groupby(meta, key=lambda v: v > 0)]
    renmu123
        2
    renmu123  
       2021-03-02 16:56:30 +08:00
    双指针吧,O(N)复杂度
    rrfeng
        3
    rrfeng  
       2021-03-02 17:02:49 +08:00
    遍历一遍不就完事儿了?
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1229 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 17:56 · PVG 01:56 · LAX 10:56 · JFK 13:56
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.