[Python-ideas] Optional key to `bisect`'s functions?
Guido van Rossum
guido at python.org
Thu Feb 9 17:41:44 CET 2012
Bingo. That clinches it. We need to add key=.
On Thu, Feb 9, 2012 at 6:27 AM, Arnaud Delobelle <arnodel at gmail.com> wrote:
> On 9 February 2012 00:25, Guido van Rossum <guido at python.org> wrote:
> > Basically Raymond says "bisect can call the key() function many times,
> which
> > leads to bad design". His alternative, to use a list of (key, value)
> tuples,
> > is often a bit clumsy when passing the sorted list to another function
> (e.g.
> > for printing); having to transform the list using e.g. [v for (k, v) in
> a]
> > feels clumsy and suboptimal.
>
> Also, in Python 3 one can't assume that values will be comparable so
> the (key, value) tuple trick won't work: comparing the tuples may well
> throw a TypeError. Here's a simple example below. The class 'Person'
> has no natural order, but we may want to keep a list of people sorted
> by iq:
>
> >>> class Person:
> ... def __init__(self, height, iq):
> ... self.height = height
> ... self.iq = iq
> ...
> >>> arno = Person(184, 101)
> >>> guido = Person(179, 185)
> >>> steve = Person(168, 101)
> >>> key = lambda p: p.iq
> >>> people = []
> >>> bisect.insort(people, (key(arno), arno))
> >>> bisect.insort(people, (key(guido), guido))
> >>> bisect.insort(people, (key(steve), steve))
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> TypeError: unorderable types: Person() < Person()
> >>>
>
> --
> Arnaud
>
--
--Guido van Rossum (python.org/~guido)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20120209/630a2dcf/attachment.html>
More information about the Python-ideas
mailing list