lambda 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'
Answer from Ashwini Chaudhary 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
Confused about using max() to find the max value of a dict. See code example
Allow `min()` and `max()` to return both the key and value - Ideas - Discussions on Python.org
numpy - How to understand the key in python max function - Stack Overflow
Why is this working? [Getting key of max value from dict]
dict={}
print(max(dict, key=dict.get)So first, why do you need the key=dict.get part? Doesn't dict.get get the value of a key? So why would you assign key=value? Shouldn't it be value=dict.get? And then you get the max value of the values?
The example code shows a python list (x) which contains one single numpy array with 10 elements. The max of that list (regardless of the key) is that numpy array.
What does
keydo?
This is a function that computes a value to each element in the list that is different from its representational value. Whichever element has the largest value as computed by this function is the max of the list.
For example:
In [109]: L = [str(i) for i in range(20)]
In [110]: L
Out[110]:
['0',
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
'10',
'11',
'12',
'13',
'14',
'15',
'16',
'17',
'18',
'19']
In [111]: max(L)
Out[111]: '9' # '9' is the lexicographically max string
In [112]: max(L, key=int)
Out[112]: '19' # 19 is the numerically max number, int('19') has this value
The example you have would have been clearer were it written like this instead:
In [106]: L = [np.array(range(i)) for i in range(1, 11)]
In [107]: L
Out[107]:
[array([0]),
array([0, 1]),
array([0, 1, 2]),
array([0, 1, 2, 3]),
array([0, 1, 2, 3, 4]),
array([0, 1, 2, 3, 4, 5]),
array([0, 1, 2, 3, 4, 5, 6]),
array([0, 1, 2, 3, 4, 5, 6, 7]),
array([0, 1, 2, 3, 4, 5, 6, 7, 8]),
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])]
In [108]: max(L, key=np.size)
Out[108]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
Your first problem is that you are using the range(10), which goes up to 10, but doesn't include the number 10. The way to go here is x =[np.array(range(11))]
And to get the max of this, using the numpy documentation, you can use np.amax, which can be done like this: res = np.amax(x) and it should work
https://numpy.org/doc/stable/reference/generated/numpy.amax.html - link for documentation.
Hey all,
I was looking for how to achieve this and found this post which did the trick, specifically the suggestion to do it like max(stats, key=stats.get)
That's good news - bad news is I don't understand how that's working and I don't like that feeling :D
More specifically, I am confused by how are we able to use .get on a dictionary and not .get(key)? Also, if there are multiple elements in the max, shouldn't it compare them all?
W3 says the syntax for each of those two is:
dictionary.get(keyname, value) - We don't do that heremax(n1, n2, n3, ...) - We don't do that here, either
So how does this approach work? I am glad I got a quick and neat solution, but feel stupid copying it blindly.