首页 > 解决方案 > 如果需要,列表理解中的索引问题

问题描述

我正在尝试获取大于阈值的值索引。但是,有些帧没有任何大于 0.5 的值。在这种情况下,我收到错误。如果不满足条件,如何解决此索引问题。

print(pred_score)

>>> [0.9752067, 0.13946067, 0.12231697, 0.10389509, 0.09314783, 0.08375313, 0.07981376, 0.06718858, 0.064989634, 0.05775991]

阈值化后

pred_t = [pred_score.index(x) for x in pred_score if x > self.threshold][-1] # Get list of index with score greater than threshold.

普通结果是:

print(pred_t)

>>>0

但是对于这种情况;

[0.29323328, 0.20563416, 0.19228794, 0.12607153, 0.112677306, 0.10169901, 0.090266354, 0.06262935, 0.062495198, 0.060448203, 0.058922235]

由于 if 条件,我收到此错误:

pred_t = [pred_score.index(x) for x in pred_score if x > self.threshold][-1] 
# Get list of index with score greater than threshold.
IndexError: list index out of range

标签: pythonlistindexing

解决方案


您需要在索引之前检查列表是否为空。你可以做这样的事情。

pred_score_threshold = [pred_score.index(x) for x in pred_score if x > self.threshold]
if pred_score_threshold:
    return pred_score_threshold[-1]

如果您使用的是 python 3.8

if res := [pred_score.index(x) for x in pred_score if x > self.threshold]:
    return res[-1]

推荐阅读