我正试图对列表进行排序,并解决Python对nan
和inf
的不良处理。
我需要将一个列表划分为所有排序(或反转)的数字,并在列表的末尾划分为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]
这不是我想要的。
我希望它只反转非nan
和inf
的值。
所需输出:
[52, 13, 8.2, 4, 3.1, nan, inf]
使用sorted
与math.isinf
和math.isnan
一起检测值是否为nan
或inf
。如果它们是实数值,则将它们取反以颠倒它们的顺序。
的例子:
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]