猿问

(Python)IndexError:列表索引超出范围

这个功能:


def assisted_by(self, players):

    text = self.event_text.split('Assisted')

    if len(text) > 1:

       print ([i for i in players if i in text[1]])

       return [i for i in players if i in text[1]][0]

    else:

       return 'N/A'

打印数百个项目并以一个空列表结束:


(...)


['Kelechi Iheanacho']

['James Maddison']

['Wilfried Zaha']

['Emiliano Buendia']

[]

返回以下错误:


  File "data_gathering.py", line 1057, in assisted_by

    return [i for i in players if i in text[1]][0]

IndexError: list index out of range

如何在不删除[0]索引的情况下修复此错误?


素胚勾勒不出你
浏览 92回答 1
1回答

宝慕林4294392

您无法从空列表中获取项目 0。您可以在尝试之前检查长度:def assisted_by(self, players):    text = self.event_text.split('Assisted')    if len(text) > 1:        data = [i for i in players if i in text[1]]        print(data)        if data:            return data[0]    return 'N/A'~
随时随地看视频慕课网APP

相关分类

Python
我要回答