Python 3.3在列表中的对上起作用

时间:2015-01-22 18:23:12

标签: list python-3.x

我正在尝试创建一个程序,它将找到列表中所有对之间的差异。例如 [2,4,6] 然后会列出包含差异的列表 [2,2] 有没有办法做到这一点

2 个答案:

答案 0 :(得分:3)

Itertools Recipespairwise

from itertools import tee

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

def diffs(iterable):
    return [b - a for a, b in pairwise(iterable)]

print(diffs([2,4,6]))

答案 1 :(得分:2)

[L[i+1] - L[i] for i in range(len(L)-1)]会这样做。

其他一些方法也使用列表理解:

[L[i+1] - L[i] for i in range(len(L[:-1]))]

[L[i] - L[i-1] for i in range(1, len(L[1:]))]

使用map

list(map(lambda i: L[i+1]-L[i], range(len(L[:-1]))))

list(map(lambda i: L[i]-L[i-1], range(1, len(L[1:]))))

使用mapoperator模块:

list(map(operator.sub, L[1:], L[:-1]))

使用zip(这可能是最好的方式,imo):

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

如果您不熟悉列表推导或使用map(GET FAMILIAR!),则会采用更详细的方法:

def differences(L1,L2):
    L = []
    for V1,V2 in zip(L1,L2):
        L.append(V2-V1)
    return L

diffs = differences(L[:-1],L[1:])

使用生成器进行类似但更好的方法:

def differences(L1,L2):
    for V1,V2 in zip(L1,L2):
        yield V2-V1

diffs = list(differences(L[:-1],L[1:]))

这是生成器理解等效于上面的生成器(注意它与上面的最后一个列表理解几乎完全相同,除了它使用list函数而不是括号):

list(V2-V1 for V1,V2 in zip(L[:-1],L[1:]))

研究所有这些非常密切的方法,你将学习很多Python。