Home > OS >  Create list based on index of existing list
Create list based on index of existing list

Time:06-05

I know how to create a new list based on the values of an existing list, eg casting

numspec = [float(x) for x in textspec]

Now I have a list of numbers where I need to subtract a value based on the index of a list. I have calculated an a and b value and ended up doing

peakadj = []
for i in range(len(peakvalues)):
    val=peakvalues[i]-(i*a b)
    peakadj.append(val)

This works, but I don't like the feel of it, is there any more pythonic way of doing this?

CodePudding user response:

Use the builtin enumerate function and a list comprehension.

peakadj = [val-(i*a b) for i, val in enumerate(peakvalues)]

CodePudding user response:

Perhaps faster:

from itertools import count

peakadj = [val-iab for val, iab in zip(peakvalues, count(b, a))]

Or:

from itertools import count
from operator import sub

peakadj = [*map(sub, peakvalues, count(b, a))]

Little benchmark

  • Related