Python列表检查2个最大值是否相同

时间:2015-07-24 10:36:16

标签: python list function max

在python中,是否可以检查列表中的2个最大值是否相同?

这是我的代码:

list=[[A, teamAScore], [B, teamBScore], [C, teamCScore], [D, teamDScore]]
list.sort()
print(max(list))

如果最大的2个值相同,则max函数将仅返回其中一个值。有没有办法检查列表中的最后两个值是否相同,所以我可以用不同的方式比较它们? (单独的功能等)

A,B,C和D是字符串。 teamAScore等是整数

1 个答案:

答案 0 :(得分:1)

我认为你想要基于得分的最大值,即第二个元素,所以首先根据每个子列表得分的第二个元素获得最大值,然后保留所有得分等于最大值的子列表:

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]]

演示:

l = [["foo", 2], ["bar", 1], ["foobar", 2]]
mx = max(l, key=itemgetter(1))

maxes = [ele for ele in l if ele[1] == mx[1]]

输出:

[['foo', 2], ['foobar', 2]]

foo和foobar的分数都等于最大值,因此我们将两个子列表都返回。