Determining whether a variable is less/greater than a range.
Tim Chase
python.list at tim.thechases.com
Mon Dec 8 12:12:02 CET 2008
> a = list(range(10, 21))
>
> b = 9
>
> c = 21
>
> How can I find out if b and c have values less or more than the values
> in list a?
Sounds like a good use for 2.5's addition of the any() and all()
functions -- you don't mention whether you want your variable
compared against *any* of the list items or *all* of the list
items. You also don't mention whether you want the comparison
results, or just a single scalar. Lastly, you omit the details
of what happens if your target value ("d" below) falls within the
range. One of the following should do it for you:
>>> a = range(10,21)
>>> b = 9
>>> c = 21
>>> d = 15
>>> any(b < x for x in a)
True
>>> all(b < x for x in a)
True
>>> any(c < x for x in a)
False
>>> any(d < x for x in a)
True
>>> all(d < x for x in a)
False
>>> any(c > x for x in a)
True
>>> all(c > x for x in a)
True
>>> any(d > x for x in a)
True
>>> all(d > x for x in a)
False
If you just want the comparisons:
y1 = [b<x for x in a]
y2 = [c<x for x in a]
y3 = [d<x for x in a]
z1 = [(b<x, b>x) for x in a]
z2 = [(c<x, c>x) for x in a]
z3 = [(d<x, d>x) for x in a]
-tkc
More information about the Python-list
mailing list