gpt4 book ai didi

python - 查找多个值相同的元组的最大值

转载 作者:太空宇宙 更新时间:2023-11-03 21:13:12 24 4
gpt4 key购买 nike

我有一个元组列表,我需要找到右侧具有最大值的元组。我还需要程序打印出具有该最大值的每个元组。我尝试过使用 lambda,但这只返回左侧具有最大值的元组之一。具体来说,我尝试过:

max(TotalFriendsList,key=lambda x:x[1])

返回(1,3)

这是列表:

[(0, 2),
(1, 3),
(2, 3),
(3, 3),
(4, 2),
(5, 3),
(6, 2),
(7, 2),
(8, 3),
(9, 1)]

这是我需要的输出:

[(1,3),
(2,3),
(3,3),
(5,3),
(8,3)]

谢谢!

最佳答案

您可以通过获取最高值,然后获取相应的元组来保持此相当紧凑:

l = [(0, 2),
(1, 3),
(2, 3),
(3, 3),
(4, 2),
(5, 3),
(6, 2),
(7, 2),
(8, 3),
(9, 1)]

# pass a generator expression to `max`
greatest = max(item[1] for item in l)

# "filter" `l`, keeping only tuples that have the greatest value as their second element
result = [item for item in l if item[1] == greatest]
print(result)
# [(1, 3), (2, 3), (3, 3), (5, 3), (8, 3)]

关于python - 查找多个值相同的元组的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54897824/

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