Python - 键值相等的频率
给定一个字典,计算键等于值的实例。
Input : test_dict = {5:5, 8:9, 7:8, 1:2, 10:10, 4:8}
Output : 2
Explanation : At 2 instances, keys are equal to values.
Input : test_dict = {5:4, 8:9, 7:8, 1:2, 10:10, 4:8}
Output : 1
Explanation : At 1 instance, key is equal to value.
方法#1:使用循环
在这种情况下,我们计算键等于值的实例并相应地增加计数器。
Python3
# Python3 code to demonstrate working of
# Keys Values equal frequency
# Using loop
# initializing dictionary
test_dict = {5: 5, 8: 9, 7: 7, 1: 2, 10: 10, 4: 8}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
res = 0
for key in test_dict:
# checking for equality and incrementing counter
if key == test_dict[key]:
res += 1
# printing result
print("The required frequency : " + str(res))
Python3
# Python3 code to demonstrate working of
# Keys Values equal frequency
# Using sum() + list comprehension
# initializing dictionary
test_dict = {5: 5, 8: 9, 7: 7, 1: 2, 10: 10, 4: 8}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# computing summation to get frequency
res = sum([1 for key in test_dict if key == test_dict[key]])
# printing result
print("The required frequency : " + str(res))
输出
The original dictionary is : {5: 5, 8: 9, 7: 7, 1: 2, 10: 10, 4: 8}
The required frequency : 3
方法 #2:使用sum() +列表理解
其中,使用 sum() 执行计数任务,当找到相等的键值时,将 1 附加到列表中,然后在最后对每个值求和。
蟒蛇3
# Python3 code to demonstrate working of
# Keys Values equal frequency
# Using sum() + list comprehension
# initializing dictionary
test_dict = {5: 5, 8: 9, 7: 7, 1: 2, 10: 10, 4: 8}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# computing summation to get frequency
res = sum([1 for key in test_dict if key == test_dict[key]])
# printing result
print("The required frequency : " + str(res))
输出
The original dictionary is : {5: 5, 8: 9, 7: 7, 1: 2, 10: 10, 4: 8}
The required frequency : 3