【问题标题】:IndexError : List index Out of range [duplicate]IndexError:列表索引超出范围[重复]
【发布时间】:2018-01-13 11:34:05
【问题描述】:

当我运行附加到 CSV 的代码时,URL 位于 columnA[1] 和 在 A[2] 处插入名称会出现以下错误:

IndexError: 列表索引超出范围

目标是通过提供 CSV 格式的名称来提取位置。

# importing the requests library
import requests
import csv

# api-endpoint
URL = "http://maps.googleapis.com/maps/api/geocode/json"

f = open("z1.csv")
reader = csv.DictReader(f)

for row in reader:
    print(row["URL"])

# location given here
location = row["URL"]

records = location.splitlines()
myreader = csv.reader(records)

for row in myreader:
    print('Location', row[0])

# Defining a params dict for the parameters to be sent to the API
PARAMS = {'address':location}

# Sending get request and saving the response as response object
r = requests.get(url = URL, params = PARAMS)

# Extracting data in json format
data = r.json()


# Extracting latitude, longitude and formatted address 
# of the first matching location
latitude = data['results'][0]['geometry']['location']['lat']
longitude = data['results'][0]['geometry']['location']['lng']
formatted_address = data['results'][0]['formatted_address']

# Printing the output
print("Latitude:%s\nLongitude:%s\nFormatted Address:%s"
%(latitude, longitude,formatted_address))

【问题讨论】:

  • 请包含完整的回溯
  • 另外,你的缩进被破坏了。
  • 我们应该猜一下,z1.csv 包含什么?请阅读How to create a Minimal, Complete, and Verifiable example 并编辑您的问题。
  • 回溯(最近一次调用最后):文件“location.py”,第 35 行,在 latitude = data['results'][0]['geometry']['location' ]['lat'] IndexError: 列表索引超出范围

标签: python json google-maps csv


【解决方案1】:

在访问其第一个元素之前,您必须确保列表 data['results'] 不为空。如果是空数组,则会引发异常IndexError : List index Out of range

还有一个建议,您需要确保results 字段存在于字典data 中。否则对data["results"] 的调用将引发KeyError 异常。在您的测试中情况并非如此。但一般来说,使用get 函数而不是括号dict.get(key) instead of dict[key] 是一个好习惯。

您的代码的修复方法是:

# importing the requests library
import requests
import csv

# api-endpoint
URL = "http://maps.googleapis.com/maps/api/geocode/json"

f = open("z1.csv")
reader = csv.DictReader(f)

for row in reader:
    print(row["URL"])

# location given here
location = row["URL"]

records = location.splitlines()
myreader = csv.reader(records)

for row in myreader:
    print('Location', row[0])

# Defining a params dict for the parameters to be sent to the API
PARAMS = {'address':location}

# Sending get request and saving the response as response object
# Make sure that you had a successful request
r = requests.get(url = URL, params = PARAMS)
if r.status_code == 200:
    # Extracting data in json format
    data = r.json()


    if data.get("results", []):
        # Extracting latitude, longitude and formatted address 
        # of the first matching location
        latitude = data['results'][0]['geometry']['location']['lat']
        longitude = data['results'][0]['geometry']['location']['lng']
        formatted_address = data['results'][0]['formatted_address']

        # Printing the output
        print("Latitude:%s\nLongitude:%s\nFormatted Address:%s"
        %(latitude, longitude,formatted_address))

【讨论】:

  • 我可以知道为什么这个更正的代码没有显示 CSV A 列中所有名称的所有位置,而是只显示最后一个元素的位置???
  • 与您的原始代码一样。这只是显示结果中的第一个元素。 formatted_address = data['results'][0]['formatted_address'] 如果你想打印所有结果,你应该简单地添加一个 for 循环来遍历结果。
猜你喜欢
  • 2019-09-22
  • 2023-04-11
  • 2012-06-23
  • 2017-11-12
  • 2017-11-03
  • 1970-01-01
  • 1970-01-01
  • 2011-10-31
相关资源
最近更新 更多