# [Tutor] how to identify a list element is in the range of a tuple element or a list element

Pujo Aji ajikoe at gmail.com
Thu Nov 17 16:13:37 CET 2005

```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,
pujo

On 11/17/05, Kent Johnson <kent37 at tds.net> 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.
> >
> >
> > 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 at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20051117/5d6aac23/attachment-0001.html
```