diff options
author | Raymond Hettinger <python@rcn.com> | 2009-06-11 22:04:00 (GMT) |
---|---|---|
committer | Raymond Hettinger <python@rcn.com> | 2009-06-11 22:04:00 (GMT) |
commit | 87be88c2e96c8e65eed703b2445c1fba169cdba2 (patch) | |
tree | 2db39b608a2e600b8494662827cfef0e5776bfc1 | |
parent | 3bca523a8c249cb244469e961790b6b56581f2d2 (diff) | |
download | cpython-87be88c2e96c8e65eed703b2445c1fba169cdba2.zip cpython-87be88c2e96c8e65eed703b2445c1fba169cdba2.tar.gz cpython-87be88c2e96c8e65eed703b2445c1fba169cdba2.tar.bz2 |
Add example of how to do key lookups with bisect().
-rw-r--r-- | Doc/library/bisect.rst | 20 |
1 files changed, 19 insertions, 1 deletions
diff --git a/Doc/library/bisect.rst b/Doc/library/bisect.rst index 93391c3..9364ed8 100644 --- a/Doc/library/bisect.rst +++ b/Doc/library/bisect.rst @@ -85,4 +85,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) |