📜  Python – 键频率,值最多为 K

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

Python – 键频率,值最多为 K

有时,在使用Python字典时,我们可能会遇到一个问题,其中我们有一个特定的值,如果它出现并且值最多为 K,我们需要找到频率。让我们讨论一些可以解决这个问题的方法。

方法#1:使用循环
这个问题可以使用简单的循环方法来解决。在这种情况下,我们只需遍历字典中的每个键,当找到匹配项时,计数器就会增加。

# Python3 code to demonstrate working of
# Keys Frequency with Value atmost K
# Using loop
  
# Initialize dictionary
test_dict = {'gfg' : 1, 'is' : 2, 'best' : 3, 'for' : 4, 'CS' : 5}
  
# printing original dictionary
print("The original dictionary : " + str(test_dict))
  
# Initialize value 
K = 3
  
# Using loop
# Keys Frequency with Value atmost K
res = 0
for key in test_dict:
    if test_dict[key] <= K:
        res = res + 1
      
# printing result 
print("Frequency of keys with values till K is : " + str(res))
输出 :
The original dictionary : {'CS': 5, 'is': 2, 'gfg': 1, 'best': 3, 'for': 4}
Frequency of keys with values till K is : 3

方法 #2:使用sum() + values()
这也可以使用 sum() 和 value() 的组合来解决。在此,sum 用于执行过滤值的求和,并使用 values() 提取字典的值。

# Python3 code to demonstrate working of
# Keys Frequency with Value atmost K
# Using sum() + values()
  
# Initialize dictionary
test_dict = {'gfg' : 1, 'is' : 2, 'best' : 3, 'for' : 4, 'CS' : 5}
  
# printing original dictionary
print("The original dictionary : " + str(test_dict))
  
# Initialize value 
K = 3
  
# Using sum() + values()
# Keys Frequency with Value atmost K
res = sum(x <= K for x in test_dict.values())
      
# printing result 
print("Frequency of keys with values till K is : " + str(res))
输出 :
The original dictionary : {'CS': 5, 'is': 2, 'gfg': 1, 'best': 3, 'for': 4}
Frequency of keys with values till K is : 3