The key argument tells the max function which max should be used. Default it will use the values of the elements itself.
dataset = [1, 1, 2, 2, 3, 4, 5, 6, 2, 1, 9, 2, 3, 2, 2, 2]
max(dataset) # 9, since 9 is the max value in this dataset
max(dataset, key=dataset.count) # 2 since 2 occurs the most in this dataset
# You can also use this:
sorted(dataset, key=dataset.count)
# [4, 5, 6, 9, 3, 3, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2]
In the last example all elements are sorted from low to high based on the count (how often is the value in the dataset).
Answer from 3dSpatialUser on Stack Overflowlambda is an anonymous function, it is equivalent to:
def func(p):
return p.totalScore
Now max becomes:
max(players, key=func)
But as def statements are compound statements they can't be used where an expression is required, that's why sometimes lambda's are used.
Note that lambda is equivalent to what you'd put in a return statement of a def. Thus, you can't use statements inside a lambda, only expressions are allowed.
What does max do?
max(a, b, c, ...[, key=func]) -> value
With a single iterable argument, return its largest item. With two or more arguments, return the largest argument.
So, it simply returns the object that is the largest.
How does key work?
By default in Python 2 key compares items based on a set of rules based on the type of the objects (for example a string is always greater than an integer).
To modify the object before comparison, or to compare based on a particular attribute/index, you've to use the key argument.
Example 1:
A simple example, suppose you have a list of numbers in string form, but you want to compare those items by their integer value.
>>> lis = ['1', '100', '111', '2']
Here max compares the items using their original values (strings are compared lexicographically so you'd get '2' as output) :
>>> max(lis)
'2'
To compare the items by their integer value use key with a simple lambda:
>>> max(lis, key=lambda x:int(x)) # compare `int` version of each item
'111'
Example 2: Applying max to a list of tuples.
>>> lis = [(1,'a'), (3,'c'), (4,'e'), (-1,'z')]
By default max will compare the items by the first index. If the first index is the same then it'll compare the second index. As in my example, all items have a unique first index, so you'd get this as the answer:
>>> max(lis)
(4, 'e')
But, what if you wanted to compare each item by the value at index 1? Simple: use lambda:
>>> max(lis, key = lambda x: x[1])
(-1, 'z')
Comparing items in an iterable that contains objects of different type:
List with mixed items:
lis = ['1','100','111','2', 2, 2.57]
In Python 2 it is possible to compare items of two different types:
>>> max(lis) # works in Python 2
'2'
>>> max(lis, key=lambda x: int(x)) # compare integer version of each item
'111'
But in Python 3 you can't do that any more:
>>> lis = ['1', '100', '111', '2', 2, 2.57]
>>> max(lis)
Traceback (most recent call last):
File "<ipython-input-2-0ce0a02693e4>", line 1, in <module>
max(lis)
TypeError: unorderable types: int() > str()
But this works, as we are comparing integer version of each object:
>>> max(lis, key=lambda x: int(x)) # or simply `max(lis, key=int)`
'111'
Strongly simplified version of max:
def max(items, key=lambda x: x):
current = item[0]
for item in items:
if key(item) > key(current):
current = item
return current
Regarding lambda:
>>> ident = lambda x: x
>>> ident(3)
3
>>> ident(5)
5
>>> times_two = lambda x: 2*x
>>> times_two(2)
4
python - Get max key in dictionary - Stack Overflow
Get the max count of values and return the key in a dictionary
python - Usage of key in max function and argument-less count method - Stack Overflow
python - Getting key with maximum value in dictionary? - Stack Overflow
This is because u'9' > u'10', since they are strings.
To compare numerically, use int as a key.
max(MyCount, key=int)
(Calling .keys() is usually unnecessary)
You need to compare the actual numerical values. Currently you're comparing the strings lexigraphically.
max(MyCount, key=int)
max() goes through the given iterable and returns the largest item.
The key parameter (also used in list.sort(), min(), and other similar functions) can be passed a function that's used to get what key to sort on. Basically, this key function is called once for each item in the iterable and that value is used for sorting instead.
The list_x.count count method is a reference to list.count(). This returns how many times the item is in the list.
Another way to write what you have would be:
max(set(list_x), key=lambda item: list_x.count(item))
It's just that instead of passing a function/lambda that calls list_x.count() to key, the list_x.count function itself was passed.
set() is being used here because a set can only contain unique elements. Since you are getting the count for each element, it is faster to use a set so you are not calling list_x.count('B') multiple times.
This computes the element in list_x that is repeated the most. set(list_x) is used to compute the max over, and for each (unique, of course) element in the set, the count of that element in the list is computed (as in list_x.count('B'), for example).
So:
list_x = ['A', 'B', 'B', 'E']
x = max(set(list_x), key=list_x.count)
# x = 'B'
list_x = ['A', 'B', 'B', 'E', 'A', 'A']
x = max(set(list_x), key=list_x.count)
# x = 'A'
max(stats, key=stats.get)
You can use operator.itemgetter for that:
import operator
stats = {'a': 1000, 'b': 3000, 'c': 100}
max(stats.iteritems(), key=operator.itemgetter(1))[0]
And instead of building a new list in memory use stats.iteritems(). The key parameter to the max() function is a function that computes a key that is used to determine how to rank items.
Please note that if you were to have another key-value pair 'd': 3000 that this method will only return one of the two even though they both have the maximum value.
>>> import operator
>>> stats = {'a': 1000, 'b': 3000, 'c': 100, 'd': 3000}
>>> max(stats.iteritems(), key=operator.itemgetter(1))[0]
'b'
If using Python3:
>>> max(stats.items(), key=operator.itemgetter(1))[0]
'b'
It happens because max does not know how to compare the elements of your dict. So if you don't provide a key, it compares them alphabetically by default. But when you give it a function, it will use that function and find max according to that function:
>>> counts = {"a": 10, "b": 5, "c": 20, "d": 15}
>>> max(counts)
'd'
>>> max(counts, key=counts.get)
'c'
max(freq) returns the maximum key in the dictionary, i.e. the last one alphabetically if the keys are strings
When you add the key=freq.get keyword argument, you get the element x with the maximum value of freq.get(x)
Given a list of number, l, can someone explain in detail why max(set(l), key=l.count) compute the mode (most frequently occurring number)? I've seen "key=" in several places and I still don't understand the meaning of it. Also why are we converting the list "l" to a set? Thanks in davance!