在 Python 列表中查找第二大数字 [英] Find a second largest number in a Python list

查看:59
本文介绍了在 Python 列表中查找第二大数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到列表中的第二大数字,并考虑将列表转换为集合,并将其转换回列表以消除重复值.不幸的是,负值采用了集合的最后一个索引(我期望最大值占据集合中的最后一个索引).列表包含负值和正值.转换为set时,负值取最后一个索引.

I was trying to find the second largest number in a list and thought of converting list into set, and to convert it back to list to eliminate the repeated values. Unfortunately, the negative value took the last index of the set (where I expected the greatest value to occupy the last index in the set). List contains both negative and positive values. When it was converted to set, the negative value took the last index.

n = 5
arr = [57, 57, 57, -57, 57]

res = list(set(arr))
print(res[-2])

我希望这是我的输出:

-57

但我得到的是:

57

如何找到列表中第二大的数字?

How do I find the second largest number in a list?

推荐答案

集合具有任意顺序.你不能依赖任何特定的顺序(它根本不是语言规范的一部分,所以它可以从一个版本到另一个版本,甚至在理论上运行到运行,在实践中对于字符串).

Sets have arbitrary ordering. You can't rely on any particular ordering (it's simply not part of the language spec, so it can change from release to release, or even run to run in theory, and in practice for strings).

要么对 list 进行排序,要么使用 heapq.nlargest 找到第二大的数字.在任何一种情况下,set 仅对重复数据删除有用,您需要转换回 list 以获得有用的排序.

Either sort the list, or use heapq.nlargest to find the second largest number. In either case, set is only useful for deduplication, you'll need to convert back to list to get useful ordering.

这篇关于在 Python 列表中查找第二大数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆