summaryrefslogtreecommitdiffstats
path: root/Doc/library/operator.rst
diff options
context:
space:
mode:
Diffstat (limited to 'Doc/library/operator.rst')
-rw-r--r--Doc/library/operator.rst52
1 files changed, 37 insertions, 15 deletions
diff --git a/Doc/library/operator.rst b/Doc/library/operator.rst
index ca056ab..590098b 100644
--- a/Doc/library/operator.rst
+++ b/Doc/library/operator.rst
@@ -428,21 +428,43 @@ 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])``.
-
-
-Examples::
-
- >>> 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)]
+ 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
+
+ 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)]
.. function:: methodcaller(name[, args...])