Reputation: 77
In python, is it possible to check if the 2 largest values in a list are the same?
This is my code:
list=[[A, teamAScore], [B, teamBScore], [C, teamCScore], [D, teamDScore]]
list.sort()
print(max(list))
If the largest 2 values are the same, the max function will only return one of them. Is there a way to check if the two last values in the list are the same, so I can compare them in a different way? (Separate function etc etc)
A, B, C and D are Strings. teamAScore etc. are integers
Upvotes: 1
Views: 1187
Reputation: 180401
I presume you want the max based on the score i.e the second element so first get the max based on the second element of each sublists scores then keep all sublists that have a score equal to the max:
from operator import itemgetter
lst = [[A, teamAScore], [B, teamBScore], [C, teamCScore], [D, teamDScore]]
# get max of list based on second element of each sublist i.e teamxScore
mx = max(lst,key=litemgetter(1)))
# use a list comp to find all sublists where teamxScore is equal to the max
maxes = [ele for ele in lst if ele[1] == mx[1]]
Demo:
l = [["foo", 2], ["bar", 1], ["foobar", 2]]
mx = max(l, key=itemgetter(1))
maxes = [ele for ele in l if ele[1] == mx[1]]
Output:
[['foo', 2], ['foobar', 2]]
Both foo and foobar had a score equal to the max so we get both sublists returned.
Upvotes: 1