Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: finding distances between list fields

Hi I need to calculate distances between every numbers pair in list, including the distance between the last and the first (it's a circle).

Naively i can do something like that:

l = [10,-12,350]
ret = []
for i in range(len(l)-1):
    ret.append(abs(l[i] - l[i+1]))
ret.append(l[-1] - l[0])
print ret

out: [22, 362, 340]

I tried "enumerate" which is a little bit better way:

print [abs(v - (l+[l[0]])[i+1]) for i, v in enumerate(l)]
out: [22, 362, 340]

Is there more elegant and "pythonic" way?

like image 568
mclafee Avatar asked Apr 30 '13 13:04

mclafee


1 Answers

I'd argue this is a small improvement. There could well be a cleaner way than this though:

print [abs(v - l[(i+1)%len(l)]) for i, v in enumerate(l)]
like image 128
andy boot Avatar answered Oct 21 '22 23:10

andy boot