我一直收到错误“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/