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
oldbird
V2EX  ›  Python

请教 Python 怎么进行列表的插值?

  •  
  •   oldbird · 2019-08-08 16:04:26 +08:00 · 3263 次点击
    这是一个创建于 1694 天前的主题,其中的信息可能已经有所发展或是发生改变。

    比如[a,b,c,d,a],希望得到 [a,(a+b)/2,b,(b+c)/2,c,(c+d)/2,d,(d+a)/2,a] 不知道有没有现成的库?

    12 条回复    2019-08-09 13:12:50 +08:00
    Ziya
        1
    Ziya  
       2019-08-08 16:10:16 +08:00
    oldbird
        2
    oldbird  
    OP
       2019-08-08 16:18:40 +08:00
    @Ziya 不是想知道 insert 方法
    junkun
        3
    junkun  
       2019-08-08 16:20:31 +08:00
    numpy.interp?
    hjq98765
        4
    hjq98765  
       2019-08-08 16:30:05 +08:00
    3 楼正解?

    我给个笨办法:


    import itertools as it

    a = range(9)
    print a

    b = list(it.chain.from_iterable([[x,x] for x in a]))
    print [(x+y)/2.0 for x,y in zip(b[:-1],b[1:])]
    smr1113
        5
    smr1113  
       2019-08-08 17:23:44 +08:00
    python:[x[0]] + [(i+j)/2.0 for i,j in zip(x,x[1:])]
    函数式:
    x.head :: (x zip x.tail map {case (x,y) => (x+y)/2.0})
    smr1113
        6
    smr1113  
       2019-08-08 17:34:25 +08:00
    看错了~~
    python:
    from itertools import chain
    list(chain(*zip(x, [(i+j)/2.0 for i,j in zip(x,x[1:])]))) + [x[-1]]
    zkqiang
        7
    zkqiang  
       2019-08-08 18:17:36 +08:00
    这种规则的不应该插值,建议像楼上那样生成新的 list
    necomancer
        8
    necomancer  
       2019-08-09 04:20:36 +08:00
    numpy 版的:
    b = np.interp(np.linspace(0,1,2*a.shape[0]-1,endpoint=1),np.linspace(0,1,a.shape[0],endpoint=1),a)
    necomancer
        9
    necomancer  
       2019-08-09 04:54:18 +08:00
    或者算符版的
    b = np.vstack([a, np.convolve([.5,.5,0],a,'same')]).ravel('F')[:-1]
    卷积里一个数组长度为常数所以应该还是 O(n) 的复杂度,不过 a 的长度必须大于等于 3,这样少生成两次用来插值的数组
    altboy
        10
    altboy  
       2019-08-09 11:18:52 +08:00
    这浏览器提醒的多明显
    ![不理智啊]( )
    source
        11
    source  
       2019-08-09 11:56:54 +08:00
    @altboy #10 老哥你回错帖了,这说的是闲鱼被骗那个贴吧
    altboy
        12
    altboy  
       2019-08-09 13:12:50 +08:00
    @source 我擦,回完就溜了,尴尬。。。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5846 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 37ms · UTC 02:26 · PVG 10:26 · LAX 19:26 · JFK 22:26
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.