Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.0k views
in Technique[技术] by (71.8m points)

arrays - Python list help (incrementing count, appending)

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:

location, lat, lon, count
San Francisco, x, y, 4
Mumbai, x1, y1, 5

Where location, lat and lon is parsed from Google geocode, count is the occurrence of that location. Eevery time a new location is added: if it exists in the list the count is incremented otherwise it is appended to the array(list) with location, lat, lon and the count should be 1.

Another example:

location, lat, lon, count
Miami x2, y2, 1 #first occurrence
San Francisco, x, y, 4 #occurred 4 times already
Mumbai, x1, y1, 5 #occurred 5 times already
Cairo, x3, y3, 1 #first occurrence

I can already get the user's location from github and can get the geocoded data from google. I just need to create this array in python which I'm struggling with.

Can anyone help me? thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

With collections.Counter, you could do :

from collections import Counter

# initial values
c=Counter({("Mumbai", 1, 2):5, ("San Francisco", 3,4): 4})

#adding entries
c.update([('Mumbai', 1, 2)])
print c  # Counter({('Mumbai', 1, 2): 6, ('San Francisco', 3, 4): 4})

c.update([('Mumbai', 1, 2), ("San Diego", 5,6)])
print c  #Counter({('Mumbai', 1, 2): 7, ('San Francisco', 3, 4): 4, ('San Diego', 5, 6): 1})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...