Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find minimum element and its position in list with Nones

I have a list of numbers and Nones like this:

l = [2., None, 3., 1., None, 2., None, 5.]

I want to get the minimum number and its index, while the Nones 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.

like image 237
piripiri Avatar asked Dec 24 '22 06:12

piripiri


2 Answers

min((v,i) for i,v in enumerate(l) if v is not None)
(1.0, 3) # (value, index)
like image 83
DYZ Avatar answered Dec 25 '22 19:12

DYZ


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.

like image 33
pstatix Avatar answered Dec 25 '22 19:12

pstatix