简体   繁体   English

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

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

I am learning python so this might sound simple, I am trying to run the code below but I keep getting the error message shown, any thoughts on what could be causing it? 我正在学习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)

The error I am getting 我得到的错误

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

The error is caused by referring element out of list range. 该错误是由于引用超出列表范围的元素引起的。 From your code, it is probably because you start counting element from 1 . 从您的代码中,可能是因为您从1开始计数元素。 Remember that in python list, index starts from 0 . 请记住,在python列表中,index从0开始。 If this is your situation, then shift indexes in 如果您遇到这种情况,则将索引移入

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

to

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

Otherwise, check your data structure and make sure it is matched with your code. 否则,请检查您的数据结构并确保它与您的代码匹配。

Thanks 谢谢

First of all make sure your CSV file has four columns. 首先,请确保您的CSV文件有四列。 Try checking if len(row) >= 4 . 尝试检查len(row) >= 4 If it contains you can go on with your code, but the first item in a Python list is referenced by 0 index. 如果包含,则可以继续执行代码,但是Python列表中的第一项由0索引引用。

Try something like this: 尝试这样的事情:

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