(Python) IndexError: list index out of range
(Python) IndexError: list index out of range
这个函数:
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]
索引的情况下修复此错误?
您无法从空列表中获取项目 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'
~
这个函数:
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]
索引的情况下修复此错误?
您无法从空列表中获取项目 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'
~