简体   繁体   中英

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

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.

>>> 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.

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

# [1, 2, 3]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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