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

How to get the values in a list with specific indices in Python?

For instance, I have

list_a = [10, 20, 30, 40, 50, 60, 70]

list_b = [10, 11, 12, nan, nan, nan, 16]

list_b is the indices of list_a, starting from 10 instead of 0. The nan elements means that the corresponding data is not of interest. The list I need is
list_c = [10, 20, 30, nan, nan, nan, 70]. How can I get it?

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 :

A simple list comprehension should get you what you want:

>>> [list_a[i] if list_b[i] is not nan else nan for i, val in enumerate(list_b)]
[10, 20, 30, nan, nan, nan, 70]

Here we’re effectively ignoring the non-nan values in list_b; we’re just treating it like a list of "boolean" nan/not-nan values.

I guess a more accurate reflection of what you wanted would be:

>>> [list_a[list_b[i]-10] if list_b[i] is not nan else nan for i, val in enumerate(list_b)]
[10, 20, 30, nan, nan, nan, 70]

But that gets you the same thing as long as the values in list_b are just an incrementing sequence (when they’re not nan).

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