如何循环而不在python上获取IndexError?

时间:2016-06-22 07:37:31

标签: python loops indexing

我试图循环url_dataurl_data是一个字符串数组。我得到一个IndexError,内容为:

keywords[i]=urlparse.urlparse(url_data[i])
IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

我的代码:

import os
import csv
import numpy as np
import pandas
import urlparse
from numpy import genfromtxt

os.chdir("C:\Users\EDAWES01\Desktop\Cookie profiling")
data = pandas.read_csv('activity_url.csv', delimiter=';')
data_read=np.array(data)
quantity = data_read[:, 2]
url_data = data_read[quantity==1][:,1] 
url_data #extract URL data

keywords=[]

for i in url_data:
  keywords[i]=urlparse.urlparse(url_data[i])
  keywords[i]=keywords[2] #this is the path element
  keywords[i]=keywords[i].split("/")

keywords

3 个答案:

答案 0 :(得分:1)

试试这个循环

for i in xrange(0,len(url_data)):
     keywords[i]=urlparse.urlparse(url_data[i])

答案 1 :(得分:1)

你做错了。如果您同时需要元素和索引,请使用enumerate()

for idx,url in enumerate(url_data):
    keywords[idx]=urlparse.urlparse(url_data[idx])
    # or it could be
    keywords[idx]=urlparse.urlparse(url)  
    # both of these will still raise IndexError for keywords

现在,来到keywords的问题是空的list,所以你也会得到IndexError。我想你想做以下事情。

keywords.append(urlparse.urlparse(url))

答案 2 :(得分:0)

从代码的外观来看,关键字应该是:

keywords = {}
keywords = dict()

print(i)找出你在做什么。