从包含None元素的列表中获取最大值

Chr*_* T. -1 python arrays numpy list nonetype

我正在尝试使用以下代码从包含nonetype的列表对象中获取最大值:

import numpy as np

LIST = [1,2,3,4,5,None]
np.nanmax(LIST)
Run Code Online (Sandbox Code Playgroud)

但我收到此错误消息

'>=' not supported between instances of 'int' and 'NoneType'
Run Code Online (Sandbox Code Playgroud)

显然np.nanmax()不适用None.从包含None值的列表对象中获取最大值的替代方法是什么?

nag*_*547 8

在Python 2中

max([i for i in LIST if i is not None])
Run Code Online (Sandbox Code Playgroud)

Python 3 及以上版本很简单

max(filter(None.__ne__, LIST))
Run Code Online (Sandbox Code Playgroud)

或者更详细地说

max(filter(lambda v: v is not None, LIST))
Run Code Online (Sandbox Code Playgroud)

  • 不要在这里使用“过滤器”。它还会丢弃零,如果您有“LIST=[-1, 0]”,这可能会成为问题。您不会期望它返回“-1”作为最大值。 (3认同)
  • 该解决方案不涵盖列表全部为 None 的情况 (2认同)

Div*_*kar 7

One approach could be -

max([i for i in LIST if i is not None])
Run Code Online (Sandbox Code Playgroud)

Sample runs -

In [184]: LIST = [1,2,3,4,5,None]

In [185]: max([i for i in LIST if i is not None])
Out[185]: 5

In [186]: LIST = [1,2,3,4,5,None, 6, 9]

In [187]: max([i for i in LIST if i is not None])
Out[187]: 9
Run Code Online (Sandbox Code Playgroud)

Based on comments from OP, it seems we could have an input list of all Nones and for that special case, it output should be [None, None, None]. For the otherwise case, the output would be the scalar max value. So, to solve for such a scenario, we could do -

a = [i for i in LIST if i is not None]
out = [None]*3 if len(a)==0 else max(a)
Run Code Online (Sandbox Code Playgroud)

  • @基督。在Python 3中,“max”接受“default”参数,因此您可以使用“max([i for i in LIST if i is not None], default=None)”,如果您的所有值都是,则将返回“None” “无”而不是失败。当然你也可以使用其他值作为默认值。 (2认同)

cs9*_*s95 5

首先,转换为numpy数组.指定dtype=np.floatX,所有这些None将被np.nan输入到类型.

import numpy as np

lst = [1, 2, 3, 4, 5, None]

x = np.array(lst, dtype=np.float64)
print(x)
array([  1.,   2.,   3.,   4.,   5.,  nan])
Run Code Online (Sandbox Code Playgroud)

现在,致电np.nanmax:

print(np.nanmax(x))
5.0
Run Code Online (Sandbox Code Playgroud)

要将max作为整数返回,您可以使用.astype:

print(np.nanmax(x).astype(int)) # or int(np.nanmax(x))
5
Run Code Online (Sandbox Code Playgroud)

这种方法适用于v1.13.1.