Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

iterating through index list of list using list comprehension

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading