迭代嵌套列表以生成忽略NoneType的最小值和最大值

问题描述 投票:1回答:1

我需要在转置的嵌套列表中找到最小值和最大值,忽略任何无类型。

这是我拥有的嵌套列表:

x = [[1, 20, 50],
     [5, 6, 7],
     [11, 42, 2],
     [7, 32, None]]

我想忽略第三列中的None,并期望得到以下输出:

min
[1, 6, 2]

max
[11,42,50]

我需要使用标准的python库来完成这个任务

python nested-lists
1个回答
2
投票

Pure py Soong Chion:

In [16]: x = [[1, 20, 50],
    ...:      [5, 6, 7],
    ...:      [11, 42, 2],
    ...:      [7, 32, None]]
    ...:

In [17]: [min((y for y in x if y is not None), default=None) for x in zip(*x)]
Out[17]: [1, 6, 2]

In [18]: [max((y for y in x if y is not None), default=None) for x in zip(*x)]
Out[18]: [11, 42, 50]

请注意,对于[[None]],上面的代码返回[None],因为既没有min也没有max元素。如果您希望此代码引发异常,请删除default=None。如果你想从结果列表中排除None,只需用[z for z in (...) if z is not None]这样的列表理解进行包装


Numpy解决方案,使用cast进行浮动以自动将None转换为nan:

In [12]: import numpy as np

In [13]: a = np.array(
    ...:     [[1, 20, 50],
    ...:      [5, 6, 7],
    ...:      [11, 42, 2],
    ...:      [7, 32, None]],
    ...:     dtype=np.float)
    ...:

In [14]: np.nanmin(a, axis=0).astype(np.int)
Out[14]: array([1, 6, 2])

In [15]: np.nanmax(a, axis=0).astype(np.int)
Out[15]: array([11, 42, 50])
© www.soinside.com 2019 - 2024. All rights reserved.