索引范围错误

时间:2012-08-17 16:35:18

标签: python

我一直收到错误'IndexError:list index out of range'

不确定我做错了什么,它适用于一对夫妇运行错误 我唯一能想到的是,我得到的名字对于变量而言太长了

        mylist = [x +'.mp3' for x in re.findall(r'file=(.*?).mp3',the_webpage)]
    #Remove Duplicates
    if mylist:
        mylist.sort()
        last = mylist[-1]
        for i in range(len(mylist)-3, -1, -1):
            if last == mylist[i]:
                del mylist[i]
            else:
                last = mylist[i]
    print " "
    #takes the quotes out of the string
    #ti = titl1[0]
    n1 = titl1[0]
    n2 = song1[0]

    #sg = song1
    sname = "".join(tuple(n1 + "-" + n2 + ".mp3"))

    print sname
    url = mylist[0]

结果

Traceback (most recent call last):
  File "grub.py", line 59, in <module>
    url = mylist[0]
IndexError: list index out of range

2 个答案:

答案 0 :(得分:6)

您的IndexError表示mylist为空,这意味着您可能删除了比您想要的更多元素(或者您的列表开头为空)。要排序和删除重复项,您可以执行

mylist = sorted(set(mylist))

即使这样,也不能保证你不会得到一个空列表(如果你的列表开始是空的,它不会神奇地获得更多的元素)。在尝试分配url之前,您还可以确保列表不为空:

#"Look Before You Leap"  (LBYL)
if mylist:  
   url = mylist[0]
else:
   url = '???'

然而,有些(大多数)会认为try - except条款更像是“pythonic”......

#Maybe it's "Easier to Ask Forgiveness than Permission" ... (EAFP)
try:
   url = mylist[0]
except IndexError:
   url = '???'

答案 1 :(得分:0)

这通常意味着mylist没有索引0,这可能意味着它实际上并不像您认为的那样是一个列表。你有一个if mylist条件,这表明可能存在一些未定义mylist的情况。也许这是其中一个案例?

相关问题