📜  Python - 测试值总和是否大于字典中的键总和

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

Python - 测试值总和是否大于字典中的键总和

给定一个字典,检查值的总和是否大于键的总和。

方法#1:使用循环

在这里,我们在单独的计数器中计算键和值的总和,并在循环对值进行相等之后,如果值大于键的总和,则返回 True。

Python3
# Python3 code to demonstrate working of
# Test if Values Sum is Greater than Keys Sum in dictionary
# 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))
  
key_sum = 0
val_sum = 0
  
for key in test_dict:
  
    # getting sum
    key_sum += key
    val_sum += test_dict[key]
  
# checking if val_sum greater than key sum
res = val_sum > key_sum
  
# printing result
print("The required result : " + str(res))


Python3
# Python3 code to demonstrate working of
# Test if Values Sum is Greater than Keys Sum in dictionary
# Using sum() + values()  + keys()
  
# 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 = sum(list(test_dict.keys())) < sum(list(test_dict.values()))
  
# printing result
print("The required result : " + str(res))


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

方法#2:使用 sum() + values() + keys()

这样,使用keys()和values()提取keys sum和values sum,使用sum()提取summation,检查所需条件并计算verdict。

蟒蛇3

# Python3 code to demonstrate working of
# Test if Values Sum is Greater than Keys Sum in dictionary
# Using sum() + values()  + keys()
  
# 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 = sum(list(test_dict.keys())) < sum(list(test_dict.values()))
  
# printing result
print("The required result : " + str(res))
输出
The original dictionary is : {5: 3, 1: 3, 10: 4, 7: 3, 8: 1, 9: 5}
The required result : False