python - 索引范围错误

标签 python

我一直收到错误“IndexError:列表索引超出范围”

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

        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

最佳答案

您的 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 = '???'

关于python - 索引范围错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12009702/

相关文章:

python - 如何使用 flask+uwsgi 服务 tensorflow 模型?

python - 将字典的长度修改为确定的值并保留具有最高值的键

python - 在 python 列表理解过程中调用 print

python - 如何在 Python 中将字符串列表转换为整数列表?

python - 多部分/混合电子邮件附件未显示,但仅在 Windows 10 邮件中显示

python - 如何在 Python 中根据列值聚合一些行

python - 使用 NetworkX 的图之间的相似性度量

python - 是否应该在 __init__ 中初始化所有成员变量

python - 如何获得两个以上类别的预测标签?

python - 无法导入 requests.packages.urllib3.util 'Retry'