# 如何在 Python 中查找列表中的最大值

## 在 Python 中使用 `for` 循环查找列表中的最大值

Python `for` 循环可以通过比较数组中的每个值并将最大的值存储在一个变量中，从而找到列表中的最大值。

``````numbers = [55, 4, 92, 1, 104, 64, 73, 99, 20]

max_value = None

for num in numbers:
if max_value is None or num > max_value:
max_value = num

print("Maximum value:", max_value)
``````

``````Maximum value: 104
``````

``````numbers = [55, 4, 92, 1, 104, 64, 73, 99, 20]

max_value = None
max_idx = None

for idx, num in enumerate(numbers):
if max_value is None or num > max_value:
max_value = num
max_idx = idx

print("Maximum value:", max_value, "At index: ", max_idx)
``````

``````Maximum value: 104 At index: 4
``````

## 在 Python 中使用 `max()` 函数查找列表中的最大值

Python 有一个预先定义的函数，叫做 `max()`，它可以返回一个列表中的最大值。

``````numbers = [55, 4, 92, 1, 104, 64, 73, 99, 20]

max_value = max(numbers)
print("Maximum value:", max_value)
``````

``````Maximum value: 104
``````

``````numbers = [55, 4, 92, 1, 104, 64, 73, 99, 20]

max_value = max(numbers)
print("Maximum value:", max_value, "At index:", arr.index(max_value))
``````

``````Maximum value: 104 At index: 4
``````

### 使用 `max()` 在字符串和字典列表中查找最大值

``````strings = ["Elephant", "Kiwi", "Gorilla", "Jaguar", "Kangaroo", "Cat"]

max_value = max(strings)
print("Maximum value:", max_value, "At index:", strings.index(max_value))
``````

``````Maximum value: Kiwi At index: 1
``````

## 在 Python 中查找嵌套列表中的最大值

``````nst = [[1001, 0.0009], [1005, 0.07682], [1201, 0.57894], [1677, 0.0977]]
``````

``````nst = [[1001, 0.0009], [1005, 0.07682], [1201, 0.57894], [1677, 0.0977]]

idx, max_value = max(nst, key=lambda item: item[1])

print("Maximum value:", max_value, "At index:", idx)
``````

`key` 参数接受一个 lambda 函数，将允许函数 `max()` 返回一个键值对。

``````Maximum value: 0.57894 At index: 1201
``````

Skilled in Python, Java, Spring Boot, AngularJS, and Agile Methodologies. Strong engineering professional with a passion for development and always seeking opportunities for personal and career growth. A Technical Writer writing about comprehensive how-to articles, environment set-ups, and technical walkthroughs. Specializes in writing Python, Java, Spring, and SQL articles.