I'm trying to sort a list and work around Python's poor handling of nan
and inf
.
I need to partition a list into all the numbers sorted (or reversed) and at the end of the list any NaN or Inf. The order of the non-number (NaN/Inf) elements is not important, so long as they are arranged at the end of the list.
For example:
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))
The o
works, and outputs:
[3.1, 4, 8.2, 13, 52, nan, inf]
But using reversed
outputs:
[inf, nan, 52, 13, 8.2, 4, 3.1]
Which is not what I want.
I want it to reverse only the values that aren't nan
and inf
.
Desired output:
[52, 13, 8.2, 4, 3.1, nan, inf]
CodePudding user response:
Use sorted
with math.isinf
and math.isnan
to detect whether it the value either is nan
or inf
. If they are real numerical values, I negate them for reversing their order.
Example:
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)
Output:
[52, 13, 8.2, 4, 3.1, nan, inf]
If you don't want to reverse
the values:
print(sorted(n))
Is enough.
Output:
[3.1, 4, 8.2, 13, 52, nan, inf]