I have a list of tuples. These tuples include an integer value and a category.
mylist = ((1,catA),(1,catB),(2,catA),..)
My objective is to select one tuple from the list that has a value = minimum value. There could be one or more of the tuples that have a value = minimum value. In the example above the minimum value is 1 and both CatA and CatB have value = minimum value.
To get min value I used:
min_value = min(mylist , key=lambda x: x[0])[0]
To select a tuple with a value = min_value I used:
min_tuple = min([x for x in mylist if x[0] == min_value])
However I would like to randomize the sort order so that the selected tuple doesn't always have the same category.
I tried using shuffle before selecting min_tuple but that didn't change the selection order.
random.shuffle(mylist)
min_tuple = min([x for x in mylist if x[0] == min_value])
So I am guessing that the min_tuple expression does it's own ordering. Is this true? If true, can the min_tuple expression ordering be randomized as it selects a tuple with value = min_value?
Edit to add:
I was aware of random.choice
from other SO question/answers and elsewhere but my question was focused on the min tuple
expression specifically how/if it ordered tuples as it found min value in list.
Also my specific formulation incorrectly or needlessly did a 'double filter' for min value
(eg == min_value
and min()
). The answer I received here corrected this usage and also applied random.choice
as a modification of my specific method.