Home > database >  iterating through index list of list using list comprehension
iterating through index list of list using list comprehension

Time:09-14

next_df = df.shift(-1)
next_waypt = next_df.values.tolist()
waypt=df.values.tolist()

So I have these 2 lists of lists from a dataframe in pandas. I want to create a new list using values from those 2 lists in a function. I do not know how to iterate over the first index however

y = [math.sin(waypt[:1][1] - next_waypt[:1][1])*math.cos(next_waypt[:1][0]) for y in waypt]

For this input I get the error "list index out of range".

y = [math.sin(waypt[y][1] - next_waypt[y][1])*math.cos(next_waypt[y][0]) for y in waypt]

for this input I get "list indices must be integers or slices". Any help would be greatly appreciated. I could just pull each column as a seperate list however it reduces code readability. I am relatively new to python so if you all think that is the best solution please let me know.

CodePudding user response:

I think your problem is that when you use your list comprehension, you are iterating over the elements of the list and not the index of it

your code should look something like this:

y = [math.sin(y[1] - next_waypt[val][1])*math.cos(next_waypt[val][0]) for val, y in enumerate(waypt)]

Note enumerate returns an index value plus an element

or this other alternative:

y = [math.sin(way[1] - next[1])*math.cos(next[0]) for way, next in zip(waypt, next_waypt)]

In this case, you zip both list and access directly to each element in the loop

  • Related