summaryrefslogtreecommitdiffstats
path: root/Doc
diff options
context:
space:
mode:
authorRaymond Hettinger <python@rcn.com>2008-03-11 21:37:46 (GMT)
committerRaymond Hettinger <python@rcn.com>2008-03-11 21:37:46 (GMT)
commit513460f80d3188978bdc5bc47936b1d0322edf9f (patch)
treebf3a24422da70a223777a43d761baeb39682980c /Doc
parent5bdff60617e6fc1d2e387a0b165cb23b82d7dae6 (diff)
downloadcpython-513460f80d3188978bdc5bc47936b1d0322edf9f.zip
cpython-513460f80d3188978bdc5bc47936b1d0322edf9f.tar.gz
cpython-513460f80d3188978bdc5bc47936b1d0322edf9f.tar.bz2
Improve docs for itemgetter(). Show that it works with slices.
Diffstat (limited to 'Doc')
-rw-r--r--Doc/library/operator.rst45
1 files changed, 33 insertions, 12 deletions
diff --git a/Doc/library/operator.rst b/Doc/library/operator.rst
index 4ab3fb1..7986ca6 100644
--- a/Doc/library/operator.rst
+++ b/Doc/library/operator.rst
@@ -517,25 +517,46 @@ expect a function argument.
.. function:: itemgetter(item[, args...])
- Return a callable object that fetches *item* from its operand. If more than one
- item is requested, returns a tuple of items. After, ``f=itemgetter(2)``, the
- call ``f(b)`` returns ``b[2]``. After, ``f=itemgetter(2,5,3)``, the call
- ``f(b)`` returns ``(b[2], b[5], b[3])``.
+ Return a callable object that fetches *item* from its operand using the
+ operand's :meth:`__getitem__` method. If multiple items are specified,
+ returns a tuple of lookup values. Equivalent to::
+
+ def itemgetter(*items):
+ if len(items) == 1:
+ item = items[0]
+ def g(obj):
+ return obj[item]
+ else:
+ def g(obj):
+ return tuple(obj[item] for item in items)
+ return g
+
+ The items can be any type accepted by the operand's :meth:`__getitem__`
+ method. Dictionaries accept any hashable value. Lists, tuples, and
+ strings accept an index or a slice::
+
+ >>> itemgetter(1)('ABCDEFG')
+ 'B'
+ >>> itemgetter(1,3,5)('ABCDEFG')
+ ('B', 'D', 'F')
+ >>> itemgetter(slice(2,None))('ABCDEFG')
+ 'CDEFG'
.. versionadded:: 2.4
.. versionchanged:: 2.5
Added support for multiple item extraction.
-Examples::
+ Example of using :func:`itemgetter` to retrieve specific fields from a
+ tuple record::
- >>> from operator import itemgetter
- >>> inventory = [('apple', 3), ('banana', 2), ('pear', 5), ('orange', 1)]
- >>> getcount = itemgetter(1)
- >>> map(getcount, inventory)
- [3, 2, 5, 1]
- >>> sorted(inventory, key=getcount)
- [('orange', 1), ('banana', 2), ('apple', 3), ('pear', 5)]
+ >>> from operator import itemgetter
+ >>> inventory = [('apple', 3), ('banana', 2), ('pear', 5), ('orange', 1)]
+ >>> getcount = itemgetter(1)
+ >>> map(getcount, inventory)
+ [3, 2, 5, 1]
+ >>> sorted(inventory, key=getcount)
+ [('orange', 1), ('banana', 2), ('apple', 3), ('pear', 5)]
.. function:: methodcaller(name[, args...])