[英]IndexError: list index out of range on simple for loop
我不知道我的代码有什么问题。 我收到此错误,但我的代码对我来说是正确的。 len(song_json['Lyrics'])
的长度为 44。
captions = ['[Intro]', '[Verse]', '[Chorus]']
for word in captions:
for i in range(len(song_json['Lyrics'])):
if word == song_json['Lyrics'][i]:
song_json['Lyrics'].remove(word)
else:
pass
IndexError:列表索引超出范围
它看起来像你想移除任何song_json['Lyrics']
这是在captions
。 你可以这样做:
song_json['Lyrics'] = [lyric for lyric in song_json['Lyrics'] if lyric not in captions]
或使用过滤器:
song_json['Lyrics'] = list(filter(lambda l: l not in captions, song_json['Lyrics']))
感谢大家的意见和建议! 这就是我将代码更改为
captions = ['[Intro]', '[Verse]', '[Chorus]']
for word in captions:
for i in song_json['Lyrics']:
if word == i:
song_json['Lyrics'].remove(word)
else:
pass
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.