📜  Python - 计算字典位置是否等于键或值

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

Python - 计算字典位置是否等于键或值

给定一个字典,计算字典项位置等于键或值的实例。适用于 Py >= 3.6 [字典排序介绍]。

方法#1:使用循环

在此我们迭代每个字典项并测试每个项以检查是否有任何位置等于字典的键或值,如果找到,我们迭代计数器。

Python3
# Python3 code to demonstrate working of
# Count if dictionary position equals key or value
# Using loop
  
# initializing dictionary
test_dict = {5: 3, 1: 3, 10: 4, 7: 3, 8: 1, 9: 5}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
res = 0
test_dict = list(test_dict.items())
for idx in range(0, len(test_dict)):
  
    # checking for key or value equality
    if idx == test_dict[idx][0] or idx == test_dict[idx][1]:
        res += 1
  
# printing result
print("The required frequency : " + str(res))


Python3
# Python3 code to demonstrate working of
# Count if dictionary position equals key or value
# Using sum() + list comprehension
  
# initializing dictionary
test_dict = {5: 3, 1: 3, 10: 4, 7: 3, 8: 1, 9: 5}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
test_dict = list(test_dict.items())
  
# sum() computing sum for filtered cases
res = sum([1 for idx in range(0, len(test_dict)) if idx ==
           test_dict[idx][0] or idx == test_dict[idx][1]])
  
# printing result
print("The required frequency : " + str(res))


输出
The original dictionary is : {5: 3, 1: 3, 10: 4, 7: 3, 8: 1, 9: 5}
The required frequency : 3

方法 #2:使用sum() +列表理解

在这种情况下,我们为发现字典索引等于其任何项目的每种情况分配 1,然后使用 sum() 执行列表求和。

蟒蛇3

# Python3 code to demonstrate working of
# Count if dictionary position equals key or value
# Using sum() + list comprehension
  
# initializing dictionary
test_dict = {5: 3, 1: 3, 10: 4, 7: 3, 8: 1, 9: 5}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
test_dict = list(test_dict.items())
  
# sum() computing sum for filtered cases
res = sum([1 for idx in range(0, len(test_dict)) if idx ==
           test_dict[idx][0] or idx == test_dict[idx][1]])
  
# printing result
print("The required frequency : " + str(res))
输出
The original dictionary is : {5: 3, 1: 3, 10: 4, 7: 3, 8: 1, 9: 5}
The required frequency : 3