简体   繁体   English

如何在python中修复索引超出范围

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

I have to extract two columns from a website. 我必须从网站中提取两列。 I know how to read the rows and print them but I'm having trouble extracting only the first and third column, every time I try to attach a variable to a row and try printing the variable it gives me an Error but if I use print(row[2]) it works but at the end it would say index out of range. 我知道如何读取行并打印它们,但是每次我尝试将变量附加到行并尝试打印变量时,我都无法仅提取第一列和第三列,但是如果我使用print,则会出现错误(row [2])它可以工作,但最后会说索引超出范围。 I don't understand why? 我不明白为什么? Here is what I did: 这是我所做的:

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)

At the very end of the data set there is an empty row which is being stored as an empty list. 在数据集的最后,有一个空行被存储为一个空列表。

You can check for this by using the following condition: 您可以使用以下条件进行检查:

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)

My attempt 我的尝试

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