📜  Python – 元组中相似键的最大值

📅  最后修改于: 2022-05-13 01:55:25.771000             🧑  作者: Mango

Python – 元组中相似键的最大值

有时,在使用Python元组时,我们可能会遇到一个问题,即我们需要执行元组列表中所有相等键值的最大值。这种应用程序在许多领域都很有用,例如 Web 开发和日常编程。让我们讨论可以执行此任务的某些方式。

方法 #1:使用 max() + groupby() + lambda + loop
上述功能的组合可以用来解决这个问题。在此,我们使用 groupby() 执行分组任务,使用 max() 提取最大值,并使用循环编译结果。

Python3
# Python3 code to demonstrate working of
# Maximum of Similar Keys in Tuples
# Using max() + groupby() + lambda + loop
from itertools import groupby
 
# initializing lists
test_list = [(4, 8), (3, 2), (2, 2), (4, 6), (3, 7), (4, 5)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Maximum of Similar Keys in Tuples
# Using max() + groupby() + lambda + loop
test_list.sort(key = lambda sub: sub[0])
temp = groupby(test_list, lambda ele: ele[0])
res = []
for key, val in temp:
    res.append((key, sum([ele[1] for ele in val])))
 
# printing result
print("Maximum grouped elements : " + str(res))


Python3
# Python3 code to demonstrate working of
# Maximum of Similar Keys in Tuples
# Using max() + groupby() + itemgetter() + list comprehension
from itertools import groupby
from operator import itemgetter
 
# initializing lists
test_list = [(4, 8), (3, 2), (2, 2), (4, 6), (3, 7), (4, 5)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Maximum of Similar Keys in Tuples
# Using max() + groupby() + itemgetter() + list comprehension
temp = groupby(sorted(test_list, key = itemgetter(0)), key = itemgetter(0))
res = [(key, max(map(itemgetter(1), sub))) for key, sub in temp]
 
# printing result
print("Maximum grouped elements : " + str(res))


输出 :
The original list is : [(4, 8), (3, 2), (2, 2), (4, 6), (3, 7), (4, 5)]
Maximum grouped elements : [(2, 2), (3, 7), (4, 8)]

方法 #2:使用 max() + groupby() + itemgetter() + 列表理解
上述功能的组合可以用来解决这个问题。在此,我们执行与上述类似的任务,使用 itemgetter 选择第二个元素,并使用列表推导来编译元素并提取结果。

Python3

# Python3 code to demonstrate working of
# Maximum of Similar Keys in Tuples
# Using max() + groupby() + itemgetter() + list comprehension
from itertools import groupby
from operator import itemgetter
 
# initializing lists
test_list = [(4, 8), (3, 2), (2, 2), (4, 6), (3, 7), (4, 5)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Maximum of Similar Keys in Tuples
# Using max() + groupby() + itemgetter() + list comprehension
temp = groupby(sorted(test_list, key = itemgetter(0)), key = itemgetter(0))
res = [(key, max(map(itemgetter(1), sub))) for key, sub in temp]
 
# printing result
print("Maximum grouped elements : " + str(res))
输出 :
The original list is : [(4, 8), (3, 2), (2, 2), (4, 6), (3, 7), (4, 5)]
Maximum grouped elements : [(2, 2), (3, 7), (4, 8)]