📜  Python – 具有最大唯一值的键

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

Python – 具有最大唯一值的键

给定一个带有值列表的字典,提取其值具有最多唯一值的键。

方法#1:使用循环

这是可以执行此任务的粗暴方式。在此,我们迭代所有列表值并检查每个键的值计数,提取具有最大唯一值的键。

Python3
# Python3 code to demonstrate working of 
# Key with maximum unique values
# Using loop
  
# initializing dictionary
test_dict = {"Gfg" : [5, 7, 5, 4, 5],
             "is" : [6, 7, 4, 3, 3], 
             "Best" : [9, 9, 6, 5, 5]}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
max_val = 0
max_key = None 
for sub in test_dict:
      
    # test for length using len()
    # converted to set for duplicates removal
    if len(set(test_dict[sub])) > max_val:
        max_val = len(set(test_dict[sub]))
        max_key = sub
  
# printing result 
print("Key with maximum unique values : " + str(max_key))


Python3
# Python3 code to demonstrate working of 
# Key with maximum unique values
# Using sorted() + lambda() + set() + values() + len()
  
# initializing dictionary
test_dict = {"Gfg" : [5, 7, 5, 4, 5],
             "is" : [6, 7, 4, 3, 3], 
             "Best" : [9, 9, 6, 5, 5]}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# one-liner to solve a problem
# sorted used to reverse sort dictionary
max_key = sorted(test_dict, key = lambda ele: len(
          set(test_dict[ele])), reverse = True)[0]
  
# printing result 
print("Key with maximum unique values : " + str(max_key))


输出

方法 #2:使用 sorted() + lambda() + set() + values() + len()

上述功能的组合可以用来解决这个问题。在此,我们根据设置的长度对字典键进行反向排序并返回第一个结果。

Python3

# Python3 code to demonstrate working of 
# Key with maximum unique values
# Using sorted() + lambda() + set() + values() + len()
  
# initializing dictionary
test_dict = {"Gfg" : [5, 7, 5, 4, 5],
             "is" : [6, 7, 4, 3, 3], 
             "Best" : [9, 9, 6, 5, 5]}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# one-liner to solve a problem
# sorted used to reverse sort dictionary
max_key = sorted(test_dict, key = lambda ele: len(
          set(test_dict[ele])), reverse = True)[0]
  
# printing result 
print("Key with maximum unique values : " + str(max_key)) 
输出