key argument for max?

Batista, Facundo FBatista at uniFON.com.ar
Thu Oct 21 12:35:17 EDT 2004


[Steven Bethard]

#- I was wondering if there's any plans to add a "key" argument to max
#- (and min) like was done for sort(ed)?  I fairly often run into a
#- situation where I have something like:
#- 
#- counts = {}
#- for item in iterable:
#-     counts[item] = counts.get(item, 0) + 1
#- _, max_item = max((count, item) for item, count in counts.items())
#- 
#- It would be nice to be able to write that last like like:
#- 
#- max(counts, key=counts.__getitem__)

Don't understand why you're doing that. I would do:

>>> lst = ['a', 'b', 'c', 'a', 'd', 'b', 'a']
>>> counts = {}
>>> for item in lst:
	counts[item] = counts.get(item, 0) + 1

>>> counts
{'a': 3, 'c': 1, 'b': 2, 'd': 1}
>>> max_item = max(counts.values())
>>> max_item
3

.	Facundo
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20041021/7c84b972/attachment.html>


More information about the Python-list mailing list