我有一个创建整数列表的函数。在某些情况下,可能会(并且会)无法确定要添加到列表中的值,所以直到现在我添加了gcr.io/my-project/hello-app:e1479a4
:
$PROJECT_ID
然后我要在列表中找到最小值的索引:
float('nan')
因此,正如您可以想象的那样,附加min_list = []
for obj in objects:
try:
min_list.append(obj.foo())
except Exception as e:
min_list.append(float('nan')) # I have to add something here,
# to get the correct index later
并没有真正的作用,我也不知道如何解决此问题。尤其是当每次调用index = min_list.index(min(min_list))
都引发一个异常(每个值都是一个float('nan')
)时,我还需要找到这种情况:
foo()
如果我具有相同数量的异常和对象,如何实现返回None值? (我也可以引发异常或返回负值)。当我无法向列表中添加正确的值时,即使出现异常,如何解决找到正确索引的问题?
答案 0 :(得分:2)
您可以这样做:
def get_min(min_list):
try:
return min_list.index(min([np.inf if val is None else val for val in min_list]))
except ValueError:
return None
list_a = [None, 3, 5, 7, None, 5]
list_b = [None, None, None]
print(get_min(list_a)) #OUTPUT 1
print(get_min(list_b)) #OUTPUT None
此方法的好处是您不必真正使用numpy
,而只需将np.inf
替换为非常高的值即可,您知道它将不可能在原始列表中(例如99999999999)
答案 1 :(得分:1)
import numpy as np
min_list = []
for obj in objects:
try:
min_list.append(obj.foo())
except Exception as e:
min_list.append(np.nan)
# ....
try:
# Case where there is at least one valid element
min_i = np.nanargmin(min_list)
except ValueError as e:
# Case where min_list is full of nan