使用python查找最大和次大元素
时间: 2024-09-15 13:02:27 浏览: 29
python topk()函数求最大和最小值实例
在Python中,你可以使用列表推导式、内置函数`max()`和`sorted()`,或者简单的遍历来找出一个列表中的最大和次大元素。以下是三种常见的方法:
**方法一:列表推导式**
```python
def find_two_largest(lst):
max_num = max(lst)
lst.remove(max_num) # 移除最大值
second_max = max(lst)
return max_num, second_max
numbers = [5, 9, 1, 7, 3]
largest, second_largest = find_two_largest(numbers)
```
**方法二:内置函数结合排序**
```python
def find_two_largest(lst):
sorted_list = sorted(lst, reverse=True)
return sorted_list[0], sorted_list[1]
numbers = [5, 9, 1, 7, 3]
largest, second_largest = find_two_largest(numbers)
```
**方法三:遍历列表**
```python
def find_two_largest(lst):
largest = second_largest = float('-inf') # 初始化为负无穷
for num in lst:
if num > largest:
second_largest = largest
largest = num
elif num > second_largest and num != largest:
second_largest = num
return largest, second_largest
numbers = [5, 9, 1, 7, 3]
largest, second_largest = find_two_largest(numbers)
```
阅读全文