xrange not hashable - why not?

Peter Otten __peter__ at web.de
Sun Jan 25 14:12:17 EST 2004


Gerrit Holl wrote:

> I was trying to do something like:
> 
> comments = {
>     xrange(0, 4): "Few",
>     xrange(4, 10): "Several",
>     xrange(10, 100): "A lot",
>     xrange(100, sys.maxint): "Can't count them"}
> for (k, v) in comments.items():
>     if n in k:
>         commentaar = v
>         break

[...]

> So, should I use one of the alternatives after all? Or does someone have
> something better to offer?

I think you want bisect():

import bisect

ranges = [
    (0, "Few"),
    (4, "Several"),
    (10, "A lot"),
    (100, "Can't count them")
]

def makelookup(r):
    bounds = [i[0] for i in r][1:]
    names = [i[1] for i in r]
    def find(value):
        return names[bisect.bisect(bounds, value)]
    return find

lookup = makelookup(ranges)

# use it
last = ""
for i in range(-100, 1000):
    if last != lookup(i):
        last = lookup(i)
        print i, last

Note that names needs one more entry than bounds. I "fixed" that by
discarding the first bounds item.

Peter



More information about the Python-list mailing list