Python – 测试偶数值字典值列表
给定一个以列表为值的字典,根据 List 中的所有值映射布尔值是否为偶数。
Input : {“Gfg” : [6, 8, 10], “is” : [8, 10, 12, 16], “Best” : [10, 16, 14, 6]}
Output : {‘Gfg’: True, ‘is’: True, ‘Best’: True}
Explanation : All lists have even numbers.
Input : {“Gfg” : [6, 5, 10], “is” : [8, 10, 11, 16], “Best” : [10, 16, 14, 6]}
Output : {‘Gfg’: False, ‘is’: False, ‘Best’: True}
Explanation : Only “Best” has even numbers.
方法#1:使用循环
这是可以执行此任务的粗暴方式。在此,我们迭代所有值并检查是否所有列表值都是即使是,我们将键分配为 True 否则为 False。
Python3
# Python3 code to demonstrate working of
# Test for Even values dictionary values lists
# Using loop
# initializing dictionary
test_dict = {"Gfg" : [6, 7, 3],
"is" : [8, 10, 12, 16],
"Best" : [10, 16, 14, 6]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
res = dict()
for sub in test_dict:
flag = 1
# checking for even elements
for ele in test_dict[sub]:
if ele % 2 != 0:
flag = 0
break
# adding True if all Even elements
res[sub] = True if flag else False
# printing result
print("The computed dictionary : " + str(res))
Python3
# Python3 code to demonstrate working of
# Test for Even values dictionary values lists
# Using all() + dictionary comprehension
# initializing dictionary
test_dict = {"Gfg" : [6, 7, 3],
"is" : [8, 10, 12, 16],
"Best" : [10, 16, 14, 6]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# using all to check for all even elements
res = {sub : all(ele % 2 == 0 for ele in test_dict[sub]) for sub in test_dict}
# printing result
print("The computed dictionary : " + str(res))
输出
The original dictionary is : {'Gfg': [6, 7, 3], 'is': [8, 10, 12, 16], 'Best': [10, 16, 14, 6]}
The computed dictionary : {'Gfg': False, 'is': True, 'Best': True}
方法 #2:使用 all() + 字典理解
这是可以执行此任务的另一种方式。在此,我们使用 all() 检查所有元素,并使用字典理解来重新制作结果。
Python3
# Python3 code to demonstrate working of
# Test for Even values dictionary values lists
# Using all() + dictionary comprehension
# initializing dictionary
test_dict = {"Gfg" : [6, 7, 3],
"is" : [8, 10, 12, 16],
"Best" : [10, 16, 14, 6]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# using all to check for all even elements
res = {sub : all(ele % 2 == 0 for ele in test_dict[sub]) for sub in test_dict}
# printing result
print("The computed dictionary : " + str(res))
输出
The original dictionary is : {'Gfg': [6, 7, 3], 'is': [8, 10, 12, 16], 'Best': [10, 16, 14, 6]}
The computed dictionary : {'Gfg': False, 'is': True, 'Best': True}