比较列表元素

时间:2011-05-29 00:48:45

标签: python

如何将一个元素与排序列表中的下一个元素进行比较,并打印出它们的差异。任何帮助将不胜感激。

Eg: 
lst = [3.18,10.57,14.95,...]
10.57 - 3.18 =  7.39
14.95 - 10.57 = 4.38
...

5 个答案:

答案 0 :(得分:6)

it = iter(lst)
it.next()
print [(x, y, y - x) for (x, y) in itertools.izip(lst, it)]

答案 1 :(得分:6)

如果您正在操纵数字数据,请考虑使用numpy

import numpy as np

lst = [3.18,10.57,14.95]
arr = np.array(lst)

diff = np.diff(arr)

>>> diff
array([ 7.39,  4.38])

如果您需要,可以将其转换回列表:

diff_list = list(diff)

否则你可以像遍历列表一样迭代它:

for item in diff: 
    print(item)

7.39
4.38

编辑:我定时的五个解决方案彼此非常接近,所以选择一个更容易阅读的解决方案

t = timeit.Timer("[b - a for a, b in zip(l, l[1:])]", "l = range(int(1e6))")
print(t.timeit(1))
>>> 0.523894071579

t = timeit.Timer("list(np.diff(np.array(l)))", "import numpy as np; l = range(int(1e6))")
print(t.timeit(1))
>>> 0.484916915894

t = timeit.Timer("diffs = [l[x + 1] - l[x] for x in range(len(l) - 1)]", "l = range(int(1e6))")
print(t.timeit(1))
>>> 0.363043069839

t = timeit.Timer("[(x, y, y - x) for (x, y) in itertools.izip(l, it)]", "l = range(int(1e6)); it = iter(l); it.next()")
print(t.timeit(1))
>>> 0.54354596138

# pairwise solution
t = timeit.Timer("a, b = itertools.tee(l); next(b, None); [(x, y) for x, y in itertools.izip(a, b)]", "l = range(int(1e6));")
print(t.timeit(1))
>>> 0.477301120758

答案 2 :(得分:4)

您需要来自recipepairwise() itertools,其中包含许多Python优点。

>>> for x,y in pairwise(lst): 
...     print(y, " - ", x, " = ", y - x)
... 
10.57  -  3.18  =  7.390000000000001
14.95  -  10.57  =  4.379999999999999

答案 3 :(得分:3)

diffs = [lst[x + 1] - lst[x] for x in range(len(lst) - 1)]
for x in diffs:
    print x 

答案 4 :(得分:3)

使用zip,并自行压缩列表。

l = [1, 2, 4, 7]
[b - a for a, b in zip(l, l[1:])]

# [1, 2, 3]