I have a list of numbers and None
s like this:
l = [2., None, 3., 1., None, 2., None, 5.]
I want to get the minimum number and its index, while the None
s should simply be ignored. For the given example, the result would thus be:
(1., 3)
Of course, it is straightforward to write a function that does what I want but I would prefer some efficient built-in or at least high-level approach.
I am particularly interested in solutions for Python 3, where the min
-function does not accept None
as an argument.
min((v,i) for i,v in enumerate(l) if v is not None)
(1.0, 3) # (value, index)
I'd probably two part it:
m = min(x for x in l if x is not None)
s = (m, l.index(m)) # this will grab the first index
If you want to make the list a single pass + one liner solution:
midx, mval = min(enumerate(x if x is not None else float('inf') for x in l), key=lambda i: i[1])
The enumerate()
piece produces an iterable like so:
0 2.0
1 inf
2 3.0
3 1.0
4 inf
5 2.0
6 inf
7 5.0
Then the min()
gets called and uses the enumerate()
return with lambda
to check the values in the i[1]
index (e.g. 2.0, inf, ..., 5.0
). Thus a final tuple is returned with only a single iteration using a generator from the original list to "filter and replace" the NoneType
indices.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With