gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 17:33:00 25 4
gpt4 key购买 nike

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

这是我的代码:

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

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

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

最佳答案

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

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 的分数都等于最大值,因此我们返回了两个子列表。

关于Python列表检查两个最大值是否相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31608321/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com