python - 如果需要,列表理解中的索引问题
问题描述
我正在尝试获取大于阈值的值索引。但是,有些帧没有任何大于 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
解决方案
您需要在索引之前检查列表是否为空。你可以做这样的事情。
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]
推荐阅读
- android - 在启动启动画面之前,反应本机 IOS 模拟器显示黑屏
- c# - Visual Studio 不创建启动文件
- unity3d - unity videoplayer 无法播放剪辑
- java - Apache HTTP WebServer 是否需要 JDK/JRE?
- javascript - 如何在 Gatsby 项目中加载 React GTM 模块
- python - 为 numpy 数组和标量设置默认浮点格式
- flutter - 在特定日期和时间颤振语言环境通知
- python - PyTorch 和 EasyOCR:避免字符串分离
- python - Tkinter - 带有 if 语句的复选框
- google-cloud-platform - 无法使用自定义模式 VPC SSH 进入 GCP 虚拟机实例