簡體   English   中英

如何在python中修復索引超出范圍

[英]How to fix Index out of range in python

我必須從網站中提取兩列。 我知道如何讀取行並打印它們,但是每次我嘗試將變量附加到行並嘗試打印變量時,我都無法僅提取第一列和第三列,但是如果我使用print,則會出現錯誤(row [2])它可以工作,但最后會說索引超出范圍。 我不明白為什么? 這是我所做的:

import urllib.request
import csv

with urllib.request.urlopen("http://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data") as webpage:
    reader = csv.reader(webpage.read().decode('utf-8').splitlines())
    for row in reader:

        cor = row[0]
        cors = row[2]
    print(cors)

在數據集的最后,有一個空行被存儲為一個空列表。

您可以使用以下條件進行檢查:

import urllib.request
import csv

with urllib.request.urlopen("http://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data") as webpage:
    reader = csv.reader(webpage.read().decode('utf-8').splitlines())
    for row in reader:
        if not row:
           continue   
        cor = row[0]
        cors = row[2]
    print(cors)

我的嘗試

import urllib
import csv

webpage =urllib.urlopen("http://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data")
reader = csv.reader(webpage.read().decode('utf-8').splitlines())
for row in reader:
    if row:
        cor = row[0]
        cors = row[2]
        print cor,cors

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM