Python list help (incrementing count, appending)

前端 未结 5 1741
小蘑菇
小蘑菇 2020-12-21 14:59

I am trying to connect google\'s geocode api and github api to parse user\'s location and create a list out of it.

The array (list) I want to create is like this:

5条回答
  •  太阳男子
    2020-12-21 15:33

    This would be better stored as a dictionary, indexed by city name. You could store it as two dictionaries, one dictionary of tuples for latitude/longitude (since lat/long never changes):

    lat_long_dict = {}
    lat_long_dict["San Francisco"] = (x, y)
    lat_long_dict["Mumbai"] = (x1, y1)
    

    And a collections.defaultdict for the count, so that it always starts at 0:

    import collections
    city_counts = collections.defaultdict(int)
    
    city_counts["San Francisco"] += 1
    city_counts["Mumbai"] += 1
    city_counts["San Francisco"] += 1
    # city counts would be
    # defaultdict(, {'San Francisco': 2, 'Mumbai': 1})
    

提交回复
热议问题