Python列表检查两个最大值是否为sam

2024-10-03 13:27:59 发布

您现在位置:Python中文网/ 问答频道 /正文

在python中,是否可以检查列表中的两个最大值是否相同?你知道吗

这是我的密码:

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

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

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


Tags: 函数字符串功能密码列表方式sortmax
1条回答
网友
1楼 · 发布于 2024-10-03 13:27:59

我假设你想要基于分数的最大值,即第二个元素,因此首先根据每个子列表分数的第二个元素得到最大值,然后保持所有分数等于最大值的子列表:

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的得分都等于max,所以我们返回了两个子列表。你知道吗

相关问题 更多 >