For循环遍历列表中的列表-索引超出范围

时间:2020-06-06 17:32:38

标签: python list for-loop

这次我不知道如何克服索引超出范围的错误。由于我的数据有时包含值,有时不包含值,并且我想保留有关列表索引的原始信息,因此将其附加到新列表上是行不通的。

如果值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

1 个答案:

答案 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