# 如何在 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.