python寻找列表中倒数第二大的数
时间: 2023-06-07 22:09:39 浏览: 101
可以通过以下代码实现:
```
lst = [12, 34, 65, 98, 23, 46, 77, 45]
max1 = max2 = float('-inf')
for num in lst:
if num > max1:
max2 = max1
max1 = num
elif num > max2 and num != max1:
max2 = num
print(max2)
```
上述代码中,我们首先初始化两个变量max1和max2为负无穷,然后遍历列表中的每个元素。如果当前元素大于max1,则将max1的值赋给max2,将当前元素的值赋给max1。如果当前元素介于max1和max2之间且不等于max1,则将当前元素的值赋给max2。最后,max2的值就是列表中的倒数第二大的数。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)