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

finding the position of an element in a nested list

just seeing if anyone can help me on my mission as I’m a little stuck. I’m trying to find all the positions of a specific nested element in multiple list. here’s a diagram to try and better explain where everything is.

data = [['name', 'city', 'height']]

there are multiple of these lists of [‘name’, ‘city’, ‘height’] in this data. I’m trying to shorten the list down to a city inputted by the user which will then find the average height and list the persons name closest to that average height.

I can get just the whole elements position but not the position in the nested list. along with the average height.

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 :

Use enumerate() to iterate over the list with its indexes. Then you can save the matching indexes in a list.

indexes = [i for i, (name, city, height) in enumerate(data) if city == search_city]

But it’s not clear that you actually need the indexes. Just use the list comprehension to filter down to that city.

matches = [el for el in data if el[1] == search_city]
avg_height = sum(el[2] for el in matches) / len(matches)
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