Python 查找列表中的最小值及其位置
在 Python 中,我们可以使用内置的 min()
函数来查找列表中的最小值。为了找到最小值的位置,我们可以使用 index()
方法。以下是一个示例代码,展示了如何查找列表中的最小值及其位置。
实例
# 定义一个列表
numbers = [34, 12, 56, 78, 23, 9]
# 查找最小值
min_value = min(numbers)
# 查找最小值的位置
min_index = numbers.index(min_value)
# 输出结果
print(f"列表中的最小值是: {min_value}")
print(f"最小值的位置是: {min_index}")
numbers = [34, 12, 56, 78, 23, 9]
# 查找最小值
min_value = min(numbers)
# 查找最小值的位置
min_index = numbers.index(min_value)
# 输出结果
print(f"列表中的最小值是: {min_value}")
print(f"最小值的位置是: {min_index}")
代码解析:
numbers = [34, 12, 56, 78, 23, 9]
:定义一个包含多个整数的列表。min_value = min(numbers)
:使用min()
函数查找列表中的最小值,并将其赋值给min_value
。min_index = numbers.index(min_value)
:使用index()
方法查找最小值在列表中的位置,并将其赋值给min_index
。print(f"列表中的最小值是: {min_value}")
:输出最小值。print(f"最小值的位置是: {min_index}")
:输出最小值的位置。
输出结果:
列表中的最小值是: 9 最小值的位置是: 5
点我分享笔记