📌  相关文章
📜  Python|具有相似值的最大键的元组

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

Python|具有相似值的最大键的元组

有时,在使用Python时,我们可能会遇到需要获取所有记录的问题。该数据可以具有相似的值,我们需要找到最大键值对。处理数据时可能会出现此类问题。让我们讨论一下可以完成此任务的某些方法。

方法 #1:使用max() + groupby() + itemgetter() + 列表理解
上述功能的组合可用于执行此特定任务。在此,我们首先使用groupby() and itemgetter()对具有相似值的元素进行分组,然后使用max()提取这些元素的最大值,并使用列表推导将结果累积到列表中。

# Python3 code to demonstrate working of
# Tuples with maximum key of similar values
# using max() + groupby() + itemgetter() + list comprehension
from operator import itemgetter
from itertools import groupby
  
# initialize list
test_list = [(4, 3), (2, 3), (3, 10), (5, 10), (5, 6)]
  
# printing original list
print("The original list : " + str(test_list))
  
# Tuples with maximum key of similar values
# using max() + groupby() + itemgetter() + list comprehension
res = [max(values) for key, values in groupby(test_list, key = itemgetter(1))]
  
# printing result
print("The records retaining maximum keys of similar values : " + str(res))
输出 :
The original list : [(4, 3), (2, 3), (3, 10), (5, 10), (5, 6)]
The records retaining maximum keys of similar values : [(4, 3), (5, 10), (5, 6)]

方法#2:使用setdefault() + items() + loop + list comprehension
以上功能的组合也可以完成这个任务。在此,我们将列表元组键值对转换为字典并使用setdefault()分配默认值。最终结果是使用列表推导计算的。

# Python3 code to demonstrate working of
# Tuples with maximum key of similar values
# using setdefault() + items() + loop + list comprehension
  
# initialize list
test_list = [(4, 3), (2, 3), (3, 10), (5, 10), (5, 6)]
  
# printing original list
print("The original list : " + str(test_list))
  
# Tuples with maximum key of similar values
# using setdefault() + items() + loop + list comprehension
temp = {}
for val, key in test_list:
  if val > temp.setdefault(key, val):
    temp[key] = val
res = [(val, key) for key, val in temp.items()]
  
# printing result
print("The records retaining maximum keys of similar values : " + str(res))
输出 :
The original list : [(4, 3), (2, 3), (3, 10), (5, 10), (5, 6)]
The records retaining maximum keys of similar values : [(4, 3), (5, 10), (5, 6)]