Improve docs for itemgetter(). Show that it works with slices.

This commit is contained in:
Raymond Hettinger 2008-03-11 21:37:46 +00:00
parent 5bdff60617
commit 513460f80d
1 changed files with 33 additions and 12 deletions

View 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...])