这次我不知道如何克服索引超出范围的错误。由于我的数据有时包含值,有时不包含值,并且我想保留有关列表索引的原始信息,因此将其附加到新列表上是行不通的。
如果值3存在,我希望打印列表中列表的所有第五个值。
wks = [["title_01", "value_02", "My Value", "", "value_04"],
["title_02", "value_03", "My Value", "", "value_05"],
["title_03"],
["title_04", "value_05", "My Value", "", "value_07"],
["title_05", "value_06"]]
for wks_list in wks:
if wks_list[2] == "My Value":
print(f"My Values in List: {wks_list[4]}")
IndexError: list index out of range
My Values in List: value_04
My Values in List: value_05
My Values in List: value_04
My Values in List: value_05
My Values in List: value_07
答案 0 :(得分:1)
只需抓住潜在的IndexError
。
for wks_list in wks:
try:
if wks_list[2] == "My Value": # IndexError can occur here
print(f"My Values in List: {wks_list[4]}") # or here
except IndexError:
pass