需要在Python中将NaN排序到列表的末尾



我正试图对列表进行排序,并解决Python对naninf的不良处理。

我需要将一个列表划分为所有排序(或反转)的数字,并在列表的末尾划分为NaN或Inf。非数字(NaN/Inf)元素的顺序并不重要,只要它们排列在列表的末尾即可。

例如:

n = [13, 4, 52, 3.1, float('nan'), float('inf'), 8.2]
print(n)
o = sorted(n, key = lambda x : float('inf') if (x != x) else x)
print(o)
print(reversed(o))

o工作,输出:

[3.1, 4, 8.2, 13, 52, nan, inf]

但使用reversed输出:

[inf, nan, 52, 13, 8.2, 4, 3.1]

这不是我想要的。

我希望它只反转非naninf的值。

所需输出:

[52, 13, 8.2, 4, 3.1, nan, inf]

使用sortedmath.isinfmath.isnan一起检测值是否为naninf。如果它们是实数值,则将它们取反以颠倒它们的顺序。

的例子:

import math
n = [13, 4, 52, 3.1, float('nan'), float('inf'), 8.2]
lst = sorted(n, key=lambda x: (math.isinf(x) or math.isnan(x), -x))
print(lst)
输出:

[52, 13, 8.2, 4, 3.1, nan, inf]

如果您不想要reverse的值:

print(sorted(n))

就足够了。输出:

[3.1, 4, 8.2, 13, 52, nan, inf]

最新更新