Python IndexError: list index out of range doesn't make sense
I am working on a little python code which parses the response from the google maps API, however I get a "IndexError: list index out of range" error, which does make any sense to me. For some requests, the code is working, for some others, not.
Purpose of the code is to structure the address response to a random address and put in a dict structure for a later use.
I checked for the range of the list (e.g. counting until n-1), but it does not seem to be an issue.
Exact traceback:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "geoCodeAPI.py", line 67, in getLocation
data[i] = {'formatted_address': formattedAddress[i], 'street': streetname[i], 'street_number': streetnumber[i], 'city': city[i], 'country': country[i], 'lat': lat[i], 'lng': lng[i]}
IndexError: list index out of range
Any suggestions and general comments to the code are highly appreciated. Thank you.
#!/usr/bin/python
import urllib
import json
jsonResponse = ''
def getLocation(rawAddressString):
addressString = rawAddressString.replace(" ", "+");
url = "http://maps.googleapis.com/maps/api/geocode/json?address=" + addressString+ "&sensor=false";
googleResponse = urllib.urlopen(url);
result = json.load(googleResponse)
formattedAddress = []
lat = []
lng = []
country = []
streetnumber = []
streetname = []
city = []
for s in result['results']:
formattedAddress.append(s['formatted_address'])
lat.append(s['geometry']['location']['lat'])
lng.append(s['geometry']['location']['lng'])
for foo in s['address_components']:
if foo['types'][0] == "country":
country.append(foo['long_name'])
else:
country.append("NA")
if foo['types'][0] == "street_number":
streetnumber.append(foo['long_name'])
else:
streetnumber.append("NA")
if foo['types'][0] == "route":
streetname.append(f开发者_运维问答oo['long_name'])
else:
streetname.append("NA")
if "locality" in foo['types'][0]:
city.append(foo['long_name'])
else:
city.append("NA")
data = dict()
print range(len(country))
print range(len(city))
for i in (range(len(country))):
data[i] = {'formatted_address': formattedAddress[i], 'street': streetname[i], 'street_number': streetnumber[i], 'city': city[i], 'country': country[i], 'lat': lat[i], 'lng': lng[i]}
return data
Don't know if it's a mistake only in the display here, but
else:
country.append("NA")
Seems to not be in the correct indentation so it'll be executed every time regardless of the condition, and you'll have a country list longer than any other list...
Your lists are not the same size. While formattedAddress, lat
and lng
have the same size as result['results']
, the lists country, streetnumber, streetname
and city
are being created in the inner loop, with one element for each s['addresscomponents']
. If you check, probably there are several "NA"
countries being created for each formattedAddress
(one for each address element that is not a country). Therefore, if you iterate over the length of country
, you will overflow formattedAddress
.
This works for me:
for s in result['results']:
formattedAddress.append(s['formatted_address'])
lat.append(s['geometry']['location']['lat'])
lng.append(s['geometry']['location']['lng'])
country.append("NA")
streetnumber.append("NA")
streetname.append("NA")
city.append("NA")
for foo in s['address_components']:
if foo['types'][0] == "country":
country[-1] = foo['long_name']
if foo['types'][0] == "street_number":
streetnumber[-1] = foo['long_name']
if foo['types'][0] == "route":
streetname[-1] = foo['long_name']
if "locality" in foo['types'][0]:
city[-1] = foo['long_name']
data = dict()
I also noticed that this error occurred when the address at a certain point in my data was wrong. So including a "ty-except" block will help catch the IndexError (or any other errors) and allow your code to keep running.
Example:
try:
'Your Code'
except IndexError:
print("Wrong Address!")
精彩评论