summaryrefslogtreecommitdiffstats
path: root/Doc/library/bisect.rst
diff options
context:
space:
mode:
authorRaymond Hettinger <python@rcn.com>2009-06-11 22:01:24 (GMT)
committerRaymond Hettinger <python@rcn.com>2009-06-11 22:01:24 (GMT)
commite046d2aefd2ef761d14feb2df8f0648a71063122 (patch)
tree98a03749708bee5587a1050bcee32edae9a4ff1e /Doc/library/bisect.rst
parent14eac1b613885da57d3182764d209e29f458d979 (diff)
downloadcpython-e046d2aefd2ef761d14feb2df8f0648a71063122.zip
cpython-e046d2aefd2ef761d14feb2df8f0648a71063122.tar.gz
cpython-e046d2aefd2ef761d14feb2df8f0648a71063122.tar.bz2
Add example of how to do key lookups with bisect().
Diffstat (limited to 'Doc/library/bisect.rst')
-rw-r--r--Doc/library/bisect.rst20
1 files changed, 19 insertions, 1 deletions
diff --git a/Doc/library/bisect.rst b/Doc/library/bisect.rst
index 61b470b..6b3f7e8 100644
--- a/Doc/library/bisect.rst
+++ b/Doc/library/bisect.rst
@@ -68,4 +68,22 @@ is a 'B', etc.
>>> map(grade, [33, 99, 77, 44, 12, 88])
['E', 'A', 'B', 'D', 'F', 'A']
-
+Unlike the :func:`sorted` function, it does not make sense for the :func:`bisect`
+functions to have *key* or *reversed* arguments because that would lead to an
+inefficent design (successive calls to bisect functions would not "remember"
+all of the previous key lookups).
+
+Instead, it is better to search a list of precomputed keys to find the index
+of the record in question::
+
+ >>> data = [('red', 5), ('blue', 1), ('yellow', 8), ('black', 0)]
+ >>> data.sort(key=lambda r: r[1]) # precomputed list of keys
+ >>> keys = [r[1] for r in data]
+ >>> data[bisect_left(keys, 0)]
+ ('black', 0)
+ >>> data[bisect_left(keys, 1)]
+ ('blue', 1)
+ >>> data[bisect_left(keys, 5)]
+ ('red', 5)
+ >>> data[bisect_left(keys, 8)]
+ ('yellow', 8)