From experiment I have relised that when in a case of a tie, python picks based on order (e.g. the item that comes in first in a list) Is there a way, where in the case of a tie i can choose an item randomly, so that it is not deterministic and based on order?
e.g.
l = [ ([1], 10) , ([2], 3), ([3], 9), ([4], 10)]
max(l, key=lambda x: x[1])
each run of this, could either return ([4], 10) or ([1], 10) and not always ([1], 10)
Python max() function The max() function returns the largest of the input values. An iterable object like string, list, tuple etc.
Passing Two or More Values to the Python max() MethodWhen two or more values are passed to the max() method, it returns the maximum or largest of them all. These arguments can be integers, floating-point values, characters or even strings. As desired, we get the maximum value, 73.
Use max() to Find Max Value in a List of Strings and Dictionaries. The function max() also provides support for a list of strings and dictionary data types in Python. The function max() will return the largest element, ordered by alphabet, for a list of strings. The letter Z is the largest value, and A is the smallest.
Shuffle the list before picking the maximum:
import random
random.shuffle(l)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With