]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
Improve docs for itemgetter(). Show that it works with slices.
authorRaymond Hettinger <python@rcn.com>
Tue, 11 Mar 2008 21:37:46 +0000 (21:37 +0000)
committerRaymond Hettinger <python@rcn.com>
Tue, 11 Mar 2008 21:37:46 +0000 (21:37 +0000)
Doc/library/operator.rst

index 4ab3fb1810f5f98907d07fbac8f91ea1f6d19d9e..7986ca6168963e8b0d2199b682557b7b839896ea 100644 (file)
@@ -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...])