在 Python 的元组列表中查找最小值和最大值
Python 要在元组列表中查找最小值和最大值:
-
使用
min()
和max()
函数。 - 将 key 参数传递给函数。
- 选择要比较的元组中的元素。
my_list = [(100, 1), (100, 2), (100, 3)]
# ✅ get min tuple in list of tuples
min_tuple = min(my_list, key=lambda tup: tup[1])
print(min_tuple) # 👉️ (100, 1)
# ------------------------------------------------------
# ✅ get max tuple in list of tuples
max_tuple = max(my_list, key=lambda tup: tup[1])
print(max_tuple) # 👉️ (100, 3)
min
函数返回可迭代对象中的最小项或两个或多个参数中最小的一个。max
函数返回可迭代对象中的最大项或两个或多个参数中最大的一个。
这些函数采用可选的默认关键字参数,用于指定在提供的可迭代对象为空时返回的值。
result = max((), default=0)
print(result) # 👉️ 0
如果可迭代对象为空且未提供默认关键字参数,则函数会引发 ValueError
。
key
参数指定一个单参数排序函数,如用于list.sort()
的函数。
my_list = [(100, 1), (100, 2), (100, 3)]
min_tuple = min(my_list, key=lambda tup: tup[1])
print(min_tuple) # 👉️ (100, 1)
我们选择索引 1 处的元组项来比较元组中的第二项。
我们还可以使用 key
参数根据不同的条件获取元组列表中的最小值和最大值。
my_list = [(100, 'a'), (100, 'ab'), (100, 'abc')]
# ✅ get value with min length in list of tuples
min_tuple = min(my_list, key=lambda tup: len(tup[1]))
print(min_tuple) # 👉️ (100, 'a')
# ------------------------------------------------------
# ✅ get value with max length in list of tuples
max_tuple = max(my_list, key=lambda tup: len(tup[1]))
print(max_tuple) # 👉️ (100, 'abc')
我们将每个元组中的第二项传递给 len()
函数以获取字符串的长度。
我们为 key 参数提供的函数可用于根据不同的条件获取最小值和最大值。
相关文章
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串
在 Python Pandas 中使用 str.split 将字符串拆分为两个列表列
发布时间:2024/04/24 浏览次数:1124 分类:Python
-
本教程介绍如何使用 pandas str.split() 函数将字符串拆分为两个列表列。
在 Pandas 中将 Timedelta 转换为 Int
发布时间:2024/04/23 浏览次数:231 分类:Python
-
可以使用 Pandas 中的 dt 属性将 timedelta 转换为整数。
Python 中的 Pandas 插入方法
发布时间:2024/04/23 浏览次数:112 分类:Python
-
本教程介绍了如何在 Pandas DataFrame 中使用 insert 方法在 DataFrame 中插入一列。
使用 Python 将 Pandas DataFrame 保存为 HTML
发布时间:2024/04/21 浏览次数:106 分类:Python
-
本教程演示如何将 Pandas DataFrame 转换为 Python 中的 HTML 表格。
如何将 Python 字典转换为 Pandas DataFrame
发布时间:2024/04/20 浏览次数:73 分类:Python
-
本教程演示如何将 python 字典转换为 Pandas DataFrame,例如使用 Pandas DataFrame 构造函数或 from_dict 方法。
如何在 Pandas 中将 DataFrame 列转换为日期时间
发布时间:2024/04/20 浏览次数:101 分类:Python
-
本文介绍如何将 Pandas DataFrame 列转换为 Python 日期时间。