buggsbunny4
buggsbunny4

Reputation: 181

Python Find Min value in a Nested List with two conditions

I am trying to get the minimum from a nested list with conditions and I am not sure how to pass two or more conditions to a minimum function in a pythonic way.

a=[['246', 'Y', '', '29386.00', '29387.00'], ['247', 'N', '', '29286.00', '29287.00'], ['248', 'N', '', '', '20919.00'], ['249', 'N', '', '20918.00', '20928.00'], ['250', 'N', '', '29266.00', '29267.00']]

In the above list, I would like to get the minimum value of 3rd element only when the 3rd element is not zero or null and when the second element in the inner list is "N".

So, for the above list example, the min value returned should be 20918 but I am getting blank.

Tried this:

>>> min(x[3] for x in a if x[1] == 'N')
''
>>> 

Thanks in Advance.

Upvotes: 1

Views: 1494

Answers (1)

Rob Gwynn-Jones
Rob Gwynn-Jones

Reputation: 687

Try this: min([x[3] for x in a if x[1] == 'N' and x[3] != ''])

The problem is:

  • the values you're comparing are strings, e.g. '20918', not integers, i.e. 20918
  • one of the x[3] values is an empty string, which is "less than" a non-empty string

Upvotes: 1

Related Questions