如何在列表中找到第二大数字? [英] How to find second largest number in a list?

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

问题描述

所以我必须从列表中查找第二大数字.我正在通过简单的循环来完成它.

So I have to find the second largest number from list. I am doing it through simple loops.

我的方法是将列表分为两部分,然后将最大的数字分为两部分,然后比较两个数字.我将从其中两个中选择较小的数字.我不能使用现成的功能或其他方法.

My approach is to divide a list into two parts and then find the largest number into two parts and then compare two numbers. I will choose the smaller number from two of them. I can not use ready functions or different approaches.

基本上,这是我的代码.但是它不能正常运行

Basically, this is my code. But it does not run correctly

#!/usr/local/bin/python2.7

alist=[-45,0,3,10,90,5,-2,4,18,45,100,1,-266,706]
largest=alist[0]
h=len(alist)/2 
m=len(alist)-h

print(alist)

for i in alist:
    if alist[h]>largest:
      largest=alist[h]
      i=i+1
print(largest)

推荐答案

O(n ^ 2)算法:

O(n^2) algorithm:

In [79]: alist=[-45,0,3,10,90,5,-2,4,18,45,100,1,-266,706]

In [80]: max(n for n in alist if n!=max(alist))
Out[80]: 100

O(n)算法:

In [81]: alist=[-45,0,3,10,90,5,-2,4,18,45,100,1,-266,706]

In [82]: M = max(alist)

In [83]: max(n for n in alist if n!=M)
Out[83]: 100

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

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