for b you can use this code:
a = [10,3,4.6,2.3,4.8,10.8,4.1]
b = ['1-4','4.1-8','8.1-12','12.1-16']
for x in a:
for y in b:
low,up = y.split('-')
if float(low) < x < float(up):
print '%s %s - %s' % (x, low, up)
break
Cheers,
b = ['1-4','4.1-8','8.1-12','12.1-16']
for x in a:
for y in b:
low,up = y.split('-')
if float(low) < x < float(up):
print '%s %s - %s' % (x, low, up)
break
Cheers,
pujo
On 11/17/05, Kent Johnson <[EMAIL PROTECTED]> wrote:
Srinivas Iyyer wrote:
> Dear group,
>
> I have a list of numbers:
>
> a = [10,3, 4.6,2.3,4.8,10.8,4.1]
> b = ['1-4','4.1-8','8.1-12','12.1-16']
> c = ((1,4),(4.1,8),(8.1-12),(12.1,16))
>
> Now I want to find if elements of list a are in the
> range of list b and in the range of tuple b.
>
> I know (and my limited knowledge on range function) is
> not allowing me to think of a new way.
>
> Could any one please help me.
>
> I wish to have the answer as:
>
> 10 8.1-12
> 3 1-4
> etc.
>
A brute-force approach is straighforward. I ignore b since it has the same values as c, and I corrected the third entry in c to be a tuple.
>>> a = [10,3, 4.6,2.3,4.8,10.8,4.1]
>>> c = ((1,4),(4.1,8),(8.1, 12),(12.1,16))
>>> for x in a:
... for lower, upper in c:
... if lower <= x <= upper:
... print '%-5s%s-%s' % (x, lower, upper)
...
10 8.1-12
3 1-4
4.6 4.1-8
2.3 1-4
4.8 4.1-8
10.8 8.1-12
4.1 4.1-8
If a and c are large this could be slow, it could be optimized by searching in c instead of exhaustive search, or by terminating the inner loop when a match is found or when lower > x.
Kent
--
http://www.kentsjohnson.com
_______________________________________________
Tutor maillist - Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
_______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor