简体   繁体   English

在包含其他数据类型的列表中查找最小 integer 值的索引

[英]Find index of smallest integer value in list containing other datatypes

I have a function which creates a list of integers.我有一个 function ,它创建一个整数列表。 Under some circumstances it can happen (and will) that I can't determine a value to add to the list, so until now I added a float('nan') :在某些情况下,可能会发生(并且将会)我无法确定要添加到列表中的值,所以直到现在我添加了一个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

Then I want to find the index of the min value in the list:然后我想在列表中找到最小值的索引:

index = min_list.index(min(min_list))

So, as you could imagine, appending float('nan') does not really work and I have no clue, how to solve this problem.所以,你可以想象,附加float('nan')并没有真正起作用,我不知道如何解决这个问题。 Especially I also need to find the case, when every call of foo() raises a Exception(every value is a float('nan') ):特别是我还需要找到这种情况,每次调用foo()都会引发异常(每个值都是float('nan') ):

nan_list = [e for e in min_list if isinstance(e, float)]
if len(nan_list) == len(min_list):
    return None
else:
    return index

How can I achieve that the None value is returned, if I have the same count of exceptions and objects?如果我有相同的异常和对象计数,如何实现返回 None 值? (I could also raise a exception or return a negative value). (我也可以引发异常或返回负值)。 And how can I satisfy the problem to find the correct index, even with a raised exception, when I can't add a correct value to the list?当我无法将正确的值添加到列表中时,即使出现异常,我如何才能满足找到正确索引的问题?

You can do:你可以做:

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

The benefit of this method is that you don't really have to use numpy for it, and just replace np.inf with a very high value, that you know there is no way it will be in the original list (like 99999999999)这种方法的好处是你真的不必为它使用numpy ,只需将np.inf替换为一个非常高的值,你知道它不可能在原始列表中(如 99999999999)

Numpy-based solution using nanargmin使用nanargmin的基于 Numpy 的解决方案

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM