繁体   English   中英

Python错误-IndexError:列表索引超出范围

[英]Python error - IndexError: list index out of range

我正在学习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

该错误是由于引用超出列表范围的元素引起的。 从您的代码中,可能是因为您从1开始计数元素。 请记住,在python列表中,index从0开始。 如果您遇到这种情况,则将索引移入

full_addy = row[1]+ "," + row[2]+ "," + row[3] + "," + row[4]

full_addy = row[0]+ "," + row[1]+ "," + row[2] + "," + row[3]

否则,请检查您的数据结构并确保它与您的代码匹配。

谢谢

首先,请确保您的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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM