SoljaragCNC
SoljaragCNC

Reputation: 45

Iterate through list and going back one item

elementList = [ 0.05, 0.07, 0.08, 0.15, 0.25, 0.32, 0.4 ]

pathLength = elementList[-1]    

itElement = iter(elementList)
for a in itElement:
    b = next(itElement)
    c = next(itElement)
    elementSize1 = b - a
    percentOfPathElement.append(elementSize1/pathLength)
    elementSize2 = c - b
    percentOfPathElement.append(elementSize2/pathLength)

I have a list of points on a curve, and I need to calculate the distance between them, and append that Value/pathLength to a list.

So I need to do:

0.07-0.05
0.08-0.07
0.15-0.08
etc...

If I run the above code, when it reaches the end of the loop, it skips one calculation because "a" goes to the next value, when I really need to go back one value.

Upvotes: 0

Views: 103

Answers (2)

matsjoyce
matsjoyce

Reputation: 5844

This is called the adjacent difference. Making your method work:

itElement = iter(elementList)
a = next(itElement)
for b in itElement:
    elementSize1 = b - a
    percentOfPathElement.append(elementSize1/pathLength)
    a = b

Printing a and b at each iteration gives:

0.05 0.07
0.07 0.08
0.08 0.15
0.15 0.25
0.25 0.32
0.32 0.4

And percentOfPathElement as:

[0.05000000000000001, 0.024999999999999988, 0.17499999999999996, 0.25, 0.17500000000000002, 0.20000000000000004]

If you need to miss out the last element, change itElement = iter(elementList) to itElement = iter(elementList[:-1]).

You can also use a list comprehension such as (modified from Kasra AD):

percentOfPathElement = [(b - a) / pathLength for a, b in zip(elementList, elementList[1:])]

Or (modified from Blckknght):

import operator
percentOfPathElement = [diff / pathLength for diff in map(operator.sub, elementList[1:], elementList)]

These work in the same way as the first version, but may be harder to understand.

Upvotes: 1

Kasravnd
Kasravnd

Reputation: 107287

You can just use zip function, to get the desire pairs then calculate the sub :

>>> elementList = [ 0.05, 0.07, 0.08, 0.15, 0.25, 0.32, 0.4 ]
>>> [j-i for i,j in zip(elementList,elementList[1:])]
[0.020000000000000004, 0.009999999999999995, 0.06999999999999999, 0.1, 0.07, 0.08000000000000002]

Upvotes: 1

Related Questions