user94628
user94628

Reputation: 3721

Incrementing variable counter when iterating through a list

I have a condition that I'm checking against each element in a list and if the condition becomes true than I want to increment the value of a counter in one of several variables. Here's my example:

for el in elements:
    if sum(x, el) < 5:
        .........DO SOMETHING: Increment variable age

Now if I want to increment the variable that relates to that el in elements how would I do it. So for example if the el was age and then I want to increment an age variable how would this be done?

I could do this by writing lots of switch statements, but what would be the most pythonic way to do it.

Thanks

EDIT

What I'm looking to do is that each element is a set of coordinates of a city(Long, Lat) and for each one I'm calculating the distance from an event. I'll be using geopy.

Now as each element is coordinates not a city name. I want to say if the event is less than 5km from the coordinates of New York to increment the New York variable or if it's 5km from London to increment the London variable.

Hope this makes it more clearer.

Upvotes: 2

Views: 3572

Answers (1)

Gareth Latty
Gareth Latty

Reputation: 89017

This is a case for a list comprehension:

[el if sum(x, el) < 5 else el + 1 for el in elements]

Edit: From your edit, I'm not really sure what you are describing matches what you said originally, what your edit says matches something like this more closely:

cities = {"London": (10, 15), "New York": (20, 50)}
def find_closest_city(location):
    ...

city_count = collections.Counter([find_closest_city(el) for el in elements])

Upvotes: 5

Related Questions