Is that what you need?
>>> a = [1100, 1140, 1258, 1800, 2100, 2365]
>>> max(x for x in a if x < 2000)
1800
>>> min(x for x in a if x > 2000)
2100
There are, fore sure, more (and maybe better) solutions.
The above solution uses so-called generator expressions (introduced in Python 2.4), i.e. this approach does not create new list objects. It just iterates through a
two times. As others have pointed out, you can reduce this to a single iteration when a
is already sorted.
Update (according to your comment above):
>>> from itertools import izip
>>> a = [1100, 1140, 1258, 1800, 2100, 2365]
>>> b = ['r', 's', 't', 'u', 'v', 'w']
>>> max((a,b) for a,b in izip(a,b) if a < 2000)
(1800, 'u')
>>> min((a,b) for a,b in izip(a,b) if a > 2000)
(2100, 'v')
This approach searches for the extrema in a list of 2-tuples, e.g. [(1100, 'r'), (1140, 's'), ...]
. This means that for searching the extrema, values from list b
are taken into consideration if values from list a
are equal, cf this answer.
Just to let you know: in order to get the exact same behavior as in the first approach, i.e. really only evaluating values from a
during extrema search, you can use
from operator import itemgetter
from itertools import izip
min(((a,b) for a,b in izip(a,b) if a > 2000)), key=itemgetter(0))
This uses item 0, i.e. the first items from the 2-tuples, i.e. values from list a
for searching the minimum.