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...]) .. function:: itemgetter(item[, args...])
Return a callable object that fetches *item* from its operand. If more than one Return a callable object that fetches *item* from its operand using the
item is requested, returns a tuple of items. After, ``f=itemgetter(2)``, the operand's :meth:`__getitem__` method. If multiple items are specified,
call ``f(b)`` returns ``b[2]``. After, ``f=itemgetter(2,5,3)``, the call returns a tuple of lookup values. Equivalent to::
``f(b)`` returns ``(b[2], b[5], b[3])``.
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 .. versionadded:: 2.4
.. versionchanged:: 2.5 .. versionchanged:: 2.5
Added support for multiple item extraction. Added support for multiple item extraction.
Examples:: Example of using :func:`itemgetter` to retrieve specific fields from a
tuple record::
>>> from operator import itemgetter >>> from operator import itemgetter
>>> inventory = [('apple', 3), ('banana', 2), ('pear', 5), ('orange', 1)] >>> inventory = [('apple', 3), ('banana', 2), ('pear', 5), ('orange', 1)]
>>> getcount = itemgetter(1) >>> getcount = itemgetter(1)
>>> map(getcount, inventory) >>> map(getcount, inventory)
[3, 2, 5, 1] [3, 2, 5, 1]
>>> sorted(inventory, key=getcount) >>> sorted(inventory, key=getcount)
[('orange', 1), ('banana', 2), ('apple', 3), ('pear', 5)] [('orange', 1), ('banana', 2), ('apple', 3), ('pear', 5)]
.. function:: methodcaller(name[, args...]) .. function:: methodcaller(name[, args...])