开发者

List comprehension for series of deltas

开发者 https://www.devze.com 2022-12-29 09:07 出处:网络
How would you write a list comprehension in python to generate a series of n-1 deltas between n items in an ordered list?

How would you write a list comprehension in python to generate a series of n-1 deltas between n items in an ordered list?

Example:

L = [5,9,2,1,7]
RES = [5-9,9-2,2-1,1-开发者_开发技巧7] = [4,7,1,6] # absolute values


RES = [abs(L[i]-L[i+1]) for i in range(len(L)-1)]


The recipes section of the itertools documentation includes source code for a function called pairwise that you can use for this purpose:

from itertools import *

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    b.next()
    return izip(a, b)

You can copy and paste this into your file. With this function defined it is quite simple to do what you want:

l = [5, 9, 2, 1, 7]
print [abs(a-b) for a,b in pairwise(l)]

Result

[4, 7, 1, 6] 


Just figured it out:

[abs(x-y) for x,y in zip(L[:-1], L[1:])]
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号