在Python中,找到列表中的第二大数值可以通过多种方法实现。以下是几种常见的方法:
方法一:排序法
```python
def find_second_largest(num_list):
tmp_list = sorted(num_list, reverse=True) 降序排序
return tmp_list 返回倒数第二个元素
num_list = [34, 11, 23, 56, 78, 0, 9, 12, 3, 7, 5]
print(find_second_largest(num_list)) 输出:78
方法二:遍历法
```python
def find_second_largest(num_list):
one = num_list
two = num_list
for i in range(1, len(num_list)):
if num_list[i] > one:
two = one
one = num_list[i]
elif num_list[i] > two:
two = num_list[i]
return two
num_list = [3, 2, 6, 4, 8, 9, 13]
print(find_second_largest(num_list)) 输出:9
方法三:使用堆(heap)
```python
import heapq
def find_second_largest(num_list):
largest = heapq.nlargest(2, num_list)[-1] 获取最大的两个数,取最后一个
num_list = [x for x in num_list if x != largest] 移除最大数
return max(num_list) 剩余数中最大的即为第二大的数
num_list = [3, 2, 6, 4, 8, 9, 13]
print(find_second_largest(num_list)) 输出:9
方法四:不使用内置函数
```python
def find_second_largest(num_list):
largest = second_largest = float('-inf')
for num in num_list:
if num > largest:
second_largest = largest
largest = num
elif num > second_largest and num != largest:
second_largest = num
return second_largest
num_list = [3, 2, 6, 4, 8, 9, 13]
print(find_second_largest(num_list)) 输出:9
以上方法各有优劣,你可以根据具体需求选择合适的方法。需要注意的是,如果列表中所有元素都相同或者列表长度小于2,这些方法可能无法正确返回第二大值。