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?
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)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With