简体   繁体   English

比较列表元素

[英]compare list elements

How can I compare one element with the next one in a sorted list, and print out their differences.如何将一个元素与排序列表中的下一个元素进行比较,并打印出它们的差异。 Any help would be appreciated.任何帮助,将不胜感激。

Eg: 
lst = [3.18,10.57,14.95,...]
10.57 - 3.18 =  7.39
14.95 - 10.57 = 4.38
...
it = iter(lst)
it.next()
print [(x, y, y - x) for (x, y) in itertools.izip(lst, it)]

If you are manipulating numerical data, consider using numpy如果您正在处理数值数据,请考虑使用 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])

You can convert it back to list if you have to:如果必须,您可以将其转换回列表:

diff_list = list(diff)

Otherwise you can iterate over it just like you iterate over a list:否则,您可以像遍历列表一样遍历它:

for item in diff: 
    print(item)

7.39
4.38

EDIT : the five solutions I timed were pretty close to each other, so choose the one that's easier to read编辑:我计时的五个解决方案彼此非常接近,所以选择一个更容易阅读的解决方案

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

You need the pairwise() recipe from itertools , from where lots of Python goodness comes.您需要来自itertools的 pairwise pairwise()配方,其中有很多 Python 的优点。

>>> for x,y in pairwise(lst): 
...     print(y, " - ", x, " = ", y - x)
... 
10.57  -  3.18  =  7.390000000000001
14.95  -  10.57  =  4.379999999999999
diffs = [lst[x + 1] - lst[x] for x in range(len(lst) - 1)]
for x in diffs:
    print x 

Use zip , and zip the list with itself.使用zip和 zip 列表与自身。

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

# [1, 2, 3]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM