Search code examples
pythonlistnested-lists

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.


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)