开发者

I keep getting "list index out of range" in Python when the list has the correct index

I am new to Python and am getting the list index error, when I shouldn't. I have the following variable:

date_array = ['2001','15','1']

I can access the first index. I can only access the last index, if I try something like this:

date_array[-1] 

I get "list index out of range" error whenever I try:

date_array[2]
date_array[1] 
开发者_如何学Python

I am attaching the complete code below for your reference:

import csv
import datetime
import re
marketReader = csv.reader(open('test.csv', 'rb'))
i=0

for row in marketReader:
    cust_id = row[0]
    date = row[1]   # Is a text. Ex: '2002-1-1'
    spent = row[2] 

    date_array = (re.split('-',date)) # Provides an array ['2002', '1', '1']
    year = date_array[0]
    month = date_array[1]
    day = date_array[2]

    # Is weekday?
    weekday=datetime.date(year,month,day).weekday()

    if i==200 and row[0]>3 :
        break
    pass
    #print(day)
    i += 1

Any help will be really appreciated! This is driving me nuts!


Simple answer is that date_array does not always have 3 elements. If you're going to index the list directly, add a check to make sure that the length is adequate.

if len(date_array) < 3:
    print('date_array too short')
    # do something else

or alternatively, wrap the index operations in a try block


Are you sure that date contains a date string separated by hyphens? If it does, this should work:

>>> import re
>>> date_array = (re.split('-',date))
>>> date_array
['2002', '1', '1']
>>> date_array[0]
'2002'
>>> date_array[1]
'1'
>>> date_array[2]
'1'

Perhaps you could add print date to verify that the date value is what you think? Also, including the traceback in your answer would help us.


If you had the correct index Python would never complain about it. If it complains, it's wrong. It's that simple.

Now figure out why the list is too short. You could print out the array and immediately see what's wrong.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜