📜  Python – 字典键的最小值配对

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

Python – 字典键的最小值配对

给定两个列表,键和值,构造一个字典,在相似键值对的情况下选择最小值。

方法#1:dict() + sorted() + zip() + lambda

上述功能的组合可以用来解决这个问题。在此,我们使用 sorted() 进行排序,zip() 用于将键映射到值。 dict() 用于将结果转换回字典。

Python3
# Python3 code to demonstrate working of 
# Minimum value pairing for dictionary keys
# Using dict() + sorted() + zip() + lambda
  
# initializing lists
test_list1 = [4, 7, 4, 8, 7, 9]
test_list2 = [5, 7, 2, 9, 3, 4]
  
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
  
# using zip() to bing key and value lists
# reverse sorting the list before assigning values 
# so as minimum values get to end, and hence avoided from 
# pairing 
res = dict(sorted(zip(test_list1, test_list2), key = lambda ele: -ele[1]))
  
# printing result 
print("The minimum paired dictionary : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Minimum value pairing for dictionary keys
# Using groupby() + itemgetter() + zip()
from operator import itemgetter
from itertools import groupby
  
# initializing lists
test_list1 = [4, 7, 4, 8, 7, 9]
test_list2 = [5, 7, 2, 9, 3, 4]
  
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
  
# using zip() to bind key and value lists
# groupby() to group similar value.
# 0th, first element is extracted to be smallest 
# using itemgetter()
temp = sorted(zip(test_list1, test_list2))
res = {key: min(val for _, val in group)
      for key, group in groupby(sorted(temp), itemgetter(0))}
  
# printing result 
print("The minimum paired dictionary : " + str(res))


输出
The original list 1 : [4, 7, 4, 8, 7, 9]
The original list 2 : [5, 7, 2, 9, 3, 4]
The minimum paired dictionary : {8: 9, 7: 3, 4: 2, 9: 4}

方法 #2:使用 groupby() + itemgetter() + zip()

上述功能的组合提供了另一种解决此问题的方法。在此,使用 groupby() 完成值分组,并使用 itemgetter() 提取最小元素。

Python3

# Python3 code to demonstrate working of 
# Minimum value pairing for dictionary keys
# Using groupby() + itemgetter() + zip()
from operator import itemgetter
from itertools import groupby
  
# initializing lists
test_list1 = [4, 7, 4, 8, 7, 9]
test_list2 = [5, 7, 2, 9, 3, 4]
  
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
  
# using zip() to bind key and value lists
# groupby() to group similar value.
# 0th, first element is extracted to be smallest 
# using itemgetter()
temp = sorted(zip(test_list1, test_list2))
res = {key: min(val for _, val in group)
      for key, group in groupby(sorted(temp), itemgetter(0))}
  
# printing result 
print("The minimum paired dictionary : " + str(res))
输出
The original list 1 : [4, 7, 4, 8, 7, 9]
The original list 2 : [5, 7, 2, 9, 3, 4]
The minimum paired dictionary : {4: 2, 7: 3, 8: 9, 9: 4}