Python 中元组列表的最大元素


当需要在元组列表(即元组列表)中找到最大元素时,可以使用 'max' 方法和 'operator.itemgetter()' 方法。itemgetter 从其操作数中获取特定项。

'max()' 方法给出传递给它的可迭代对象中存在最大值。以下是一些在元组列表中查找最大元素的常用方法。

  • 'itemgetter()' 函数:用于从可迭代对象(如列表、元组或字典)中检索项目。

  • 'max()' + 'zip()' 函数:使用 map() 函数将元素链接到 zip 函数以提取最大值。

  • 使用 for 循环 +'min()' + 'max()':使用 for 循环遍历元组列表并存储最大元组。

  • 使用 enumerate 函数:此方法涉及使用 for 循环迭代,并且我们同时获得索引值和元素。

使用 'itemgetter()' 函数

此函数允许您指定要从可迭代对象(如列表、元组或字典)中检索项目的项目的索引或键。

使用 'itemgetter()' 而不是传统的索引或键值查找,因为它可用于根据多个键对复杂数据结构进行排序。

示例

我们需要从 operator 模块导入 itemgetter() 函数。在下面的示例中,我们使用带 itemgetter() 的 max 函数根据第二个元素(值)查找具有最高值的元组。

from operator import itemgetter
my_list = [('Will', 23), ('Jane', 21), ('El', 24), ('Min', 101)]

print ("The list is : ")
print(my_list)

my_result = max(my_list, key = itemgetter(1))[0]

print ("The name that has the maximum value is : ")
print(my_result)

输出

The list is :
[('Will', 23), ('Jane', 21), ('El', 24), ('Min', 101)]
The name that has the maximum value is :
Min

使用 'max()' 和 'zip()'

map() 函数链接到 zip() 函数,这些函数收集元素以执行 max() 函数的功能。在下面的示例中,zip(*test_list) 转置元组列表,有效地将所有第一个元素和所有第二个元素组合在一起。

test_list = [(2, 3), (4, 7), (8, 11), (3, 6)]
 
# printing original list
print ("The original list is : " + str(test_list))
 
# using map() + zip()
res1 = list(map(max, zip(*test_list)))

# printing result 
print ("Maximum Value : " + str(res1))

输出

The original list is : [(2, 3), (4, 7), (8, 11), (3, 6)]
Maximum Value : [8, 11]

使用 for 循环和 'min()' 和 'max()' 方法。

使用 for 循环遍历元组列表,将第一个和第二个位置存储在两个 列表 中,并将最大值存储在两个 元组 中。以下示例迭代 test_list 中的每个元组,将第一个元素附加到 x,将第二个元素附加到 y。

test_list = [(2, 3), (4, 7), (8, 11), (3, 6)]
 
# printing original list
print ("The original list is : " + str(test_list))
 
# using min() and max()
# to get min and max in list of tuples
x=[]
y=[]
for i in test_list:
    x.append(i[0])
    y.append(i[1])
res1=(max(x),max(y))

# printing result
print ("Max value: " + str(res1))

输出

The original list is : [(2, 3), (4, 7), (8, 11), (3, 6)]
Max value: (8, 11)

使用 enumerate 函数

enumerate() 函数返回给定可迭代对象的枚举对象,这使我们能够使用 for 循环进行迭代。使用它,我们同时获得索引值和元素。此函数提供了一种在迭代列表中的项目时跟踪索引的方法,而无需手动管理索引。我们可以使用 enumerate 函数找到元素的最大值。

示例

以下是使用 enumerate() 函数在元组列表中查找最大元素的示例 -

tup_list = [(2, 74), (6, 7), (95, 1), (6, 10), (18, 7)] 
print("Original List:",tup_list)
max_list = [j for a,i in enumerate(tup_list) for j in i ]
print("Maximum Number :",max(max_list))

输出

以下是上述代码的输出 -

Original List: [(2, 74), (6, 7), (95, 1), (6, 10), (18, 7)]
Maximum Number : 95

更新于: 2024年10月9日

2K+ 次查看

启动您的 职业生涯

通过完成课程获得认证

开始
广告

© . All rights reserved.