我正在学习python所以这可能听起来很简单,我正在尝试运行下面的代码,但我不断收到显示的错误信息,对可能导致它的原因有什么想法?
from geopy import geocoders
import csv
g_api_key = 'my_google_api_key'
g = geocoders.GoogleV3(g_api_key)
costco = csv.reader (open('costcolimited.csv'), delimiter = ',')
# Print header
print "Address, City, State, Zip Code, Latitude, Longitude"
for row in costco:
full_addy = row[1]+ "," + row[2]+ "," + row[3] + "," + row[4]
place, (lat,lng) = list (g.geocode(full_addy, exactly_one=FALSE))[0]
full_addy + "," + str(lat) + "," + str(lng)
我得到的错误
Traceback (most recent call last):
File "C:\Python27\geocodelocations.py", line 12, in <module>
full_addy = row[1]+ "," + row[2]+ "," + row[3] + "," + row[4]
IndexError: list index out of range
答案 0 :(得分:0)
错误是由引用元素超出列表范围引起的。从您的代码中,可能是因为您从1
开始计算元素。请记住,在python列表中,索引从0
开始。如果这是你的情况,那么在
full_addy = row[1]+ "," + row[2]+ "," + row[3] + "," + row[4]
到
full_addy = row[0]+ "," + row[1]+ "," + row[2] + "," + row[3]
否则,请检查您的数据结构并确保它与您的代码匹配。
由于
答案 1 :(得分:0)
首先确保您的CSV文件有四列。尝试检查是否len(row) >= 4
。如果它包含你可以继续你的代码,但Python列表中的第一项由0索引引用。
尝试这样的事情:
for row in costco:
if len(row) < 4:
print "Invalid file!"
break
full_addy = row[0]+ "," + row[1]+ "," + row[2] + "," + row[3]
place, (lat,lng) = list (g.geocode(full_addy, exactly_one=FALSE))[0]
full_addy + "," + str(lat) + "," + str(lng)