Find a second largest number in a Python list [duplicate]

寵の児 提交于 2019-12-14 03:05:11

问题


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

I expected this to be my output:

-57

but the one I got was:

57

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


回答1:


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).

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.




回答2:


Here

arr = [57, 57, 57, -57, 57]

# If you want to avoid duplicates:
second_largest  = sorted(list(set(arr)))[-2]


# If you dont care about duplicates:
second_largest = sorted(arr)[-2]


来源:https://stackoverflow.com/questions/56514869/find-a-second-largest-number-in-a-python-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!