python获得列表中第二大的元素值

 第一种方法:仅需使用sort()pop()来实现

list26 = [ 1, 13, 5, 6, 11, 12, 7, 8, 13]
list26.sort()                                        # 先对列表元素按从小到大进行排序
count = list26.count(list26[len(list26) - 1] )       # list26[ len(list26) - 1 ]获得列表中最大元素的下标值,count(……)获得最大元素在列表中出现的次数
c = 0
while c < count:                                     # 使用while循环通过最大值出现的次数决定循环次数
    list26.pop()                                     # 使用pop()默认删除列表最后的元素,即最大元素,删除次数取决于循环次数即count()的值
    c += 1
print(list26[len(list26) - 1])                       # 打印列表最后一个元素,即未删除最大元素之前的第二大值

第二种方法: 仅使用 if 判断和 while 循环

list27 = [ ]
num1 = 0
while num1 < 5:
    val1 = int(input("请输入五个数字存入列表:  "))
    list27.append(val1)
    num1 += 1
print("接下来将选出你所输入数字的第二大值:")
max = 0
sec = 0
if list27[0] > list27[1]:
    max = list27[0]
    sec = list27[1]
else:
    max = list27[1]
    sec = list27[0]
index = 2
while index < len(list27):
    if list27[index] > max:
        sec = max
        max = list27[index]
    index += 1

print(sec)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值