Home > Enterprise >  Making a loop to calculate [n] - [n 1] inside a single python list
Making a loop to calculate [n] - [n 1] inside a single python list

Time:09-14

I'm trying to calculate, with a loop, a substraction between n element and n 1 element inside a single python list.

For exemple :

list = [26.5, 17.3, 5.9, 10.34, 3.87]

    # expected calculation
    # 26.5 - 17.3 = 9.2
    # 17.3 - 5.9 = 11.4
    # ...

    # expected result
    # list_2 = [9.2, 11.4, -4.44, 6.47]

I tried with :

list_2 = [n-(n 1) for n in list]
    # output
    # [-1.0, -1.0, -1.0, -1.0, -1.0]

-----------------------------------------
list_2 = []
for n in list:
    list_2  = list[n] - list[n 1]
    # output
    # TypeError: list indices must be integers or slices, not float
    
    # with correction of 'TypeError'
    list_2  = list[int(n)] - list[int(n 1)]
    # output
    # TypeError: 'float' object is not iterable

The problem look simple but... I can't do it. Do you have an idea? If it is possible, I'm looking for a native python3 solution.

Thank you per advance and have a nice day/evening.

CodePudding user response:

Try this.

l = [26.5, 17.3, 5.9, 10.34, 3.87]

result = [l[i] - l[i   1] for i in range(len(l) - 1)]

CodePudding user response:

You can use zip and slice

 zip(*iterables, strict=False)

Iterate over several iterables in parallel, producing tuples with an item from each one.

>>> result = [current-_next for current,_next in zip(l,l[1:])]
>>> result
[9.2, 11.4, -4.4399999999999995, 6.47]

NOTE: The third result is unprecise because of floating point math

  • Related