遍历嵌套列表以生成忽略 NoneType 的最小值和最大值
Iterating through a nested list to produce min and max values ignoring NoneType
我需要在转置嵌套列表中找到最小值和最大值,忽略任何 none 类型。
这是我的嵌套列表:
x = [[1, 20, 50],
[5, 6, 7],
[11, 42, 2],
[7, 32, None]]
我想忽略第三列中的 None 并希望得到以下输出:
min
[1, 6, 2]
max
[11,42,50]
我需要使用标准 python 库
纯python溶液:
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]]
上面的代码 returns [None]
因为既没有最小元素也没有最大元素。如果您希望此代码引发异常,只需删除 default=None
。如果您想从结果列表中排除 None
,只需用 [z for z in (...) if z is not None]
这样的列表理解包装
Numpy 解决方案,强制转换为浮点数以自动将 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])
我需要在转置嵌套列表中找到最小值和最大值,忽略任何 none 类型。
这是我的嵌套列表:
x = [[1, 20, 50],
[5, 6, 7],
[11, 42, 2],
[7, 32, None]]
我想忽略第三列中的 None 并希望得到以下输出:
min
[1, 6, 2]
max
[11,42,50]
我需要使用标准 python 库
纯python溶液:
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]]
上面的代码 returns [None]
因为既没有最小元素也没有最大元素。如果您希望此代码引发异常,只需删除 default=None
。如果您想从结果列表中排除 None
,只需用 [z for z in (...) if z is not None]
Numpy 解决方案,强制转换为浮点数以自动将 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])