Jamie Cook
Jamie Cook

Reputation: 25

Iterating through a nested list to produce min and max values ignoring NoneType

I need to find the min and max values in a transposed nested list, ignoring any none types.

This the nested list I have:

x = [[1, 20, 50],
     [5, 6, 7],
     [11, 42, 2],
     [7, 32, None]]

I am wanting to ignore the None in the third column and would expect to have the following output:

min
[1, 6, 2]

max
[11,42,50]

I need to do this using the standard python library

Upvotes: 1

Views: 186

Answers (1)

awesoon
awesoon

Reputation: 33651

Pure python solution:

In [16]: x = [[1, 20, 50],
    ...:      [5, 6, 7],
    ...:      [11, 42, 2],
    ...:      [7, 32, None]]
    ...:

In [17]: [min((y for y in x if y is not None), default=None) for x in zip(*x)]
Out[17]: [1, 6, 2]

In [18]: [max((y for y in x if y is not None), default=None) for x in zip(*x)]
Out[18]: [11, 42, 50]

Note that for [[None]] the code above returns [None] as there are neither no min nor max elements. If you want this code to raise an exception just remove default=None. If you want to exclude None from the resulting list just wrap with a list comprehension like [z for z in (...) if z is not None]


Numpy solution with casting to float to automatically convert None to nan:

In [12]: import numpy as np

In [13]: a = np.array(
    ...:     [[1, 20, 50],
    ...:      [5, 6, 7],
    ...:      [11, 42, 2],
    ...:      [7, 32, None]],
    ...:     dtype=np.float)
    ...:

In [14]: np.nanmin(a, axis=0).astype(np.int)
Out[14]: array([1, 6, 2])

In [15]: np.nanmax(a, axis=0).astype(np.int)
Out[15]: array([11, 42, 50])

Upvotes: 2

Related Questions