📌  相关文章
📜  Python程序检查是否有任何键具有所有给定的列表元素

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

Python程序检查是否有任何键具有所有给定的列表元素

给定一个包含列表值和列表的字典,任务是编写一个Python程序来检查是否有任何键包含所有列表元素。

例子:

方法 #1:使用issuperset() +循环

在此,我们使用 issuperset() 执行查找值列表中所有元素是否存在的任务,并使用循环来迭代所有键。

Python3
# Python3 code to demonstrate working of
# Extract values of Particular Key in
# Nested Values Using list comprehension
  
# initializing dictionary
test_dict = {'Gfg': [5, 3, 1, 6, 4], 
             'is': [8, 2, 1, 6, 4], 
             'best': [1, 2, 7, 3, 9],
             'for': [5, 2, 7, 8, 4, 1], 
             'all': [8, 5, 3, 1, 2]}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# initializing list
find_list = [7, 9, 2]
  
res = False
for key in test_dict:
  
    # checking if all values present using 
    # superset
    if set(test_dict[key]).issuperset(find_list):
        res = True
  
# printing result
print("Is any value list superset ? : " + str(res))


Python3
# Python3 code to demonstrate working of
# Extract values of Particular Key in
# Nested Values Using any() + issuperset()
  
# initializing dictionary
test_dict = {'Gfg': [5, 3, 1, 6, 4],
             'is': [8, 2, 1, 6, 4],
             'best': [1, 2, 7, 3, 9],
             'for': [5, 2, 7, 8, 4, 1],
             'all': [8, 5, 3, 1, 2]}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# initializing list
find_list = [7, 9, 2]
  
res = any(set(sub).issuperset(find_list) 
          for sub in test_dict.values())
  
# printing result
print("Is any value list superset ? : " + str(res))


输出:

方法#2:使用any() + issuperset()

在这里,我们使用 any() 执行检查所有键的任务。其余所有功能与上述方法类似。

蟒蛇3

# Python3 code to demonstrate working of
# Extract values of Particular Key in
# Nested Values Using any() + issuperset()
  
# initializing dictionary
test_dict = {'Gfg': [5, 3, 1, 6, 4],
             'is': [8, 2, 1, 6, 4],
             'best': [1, 2, 7, 3, 9],
             'for': [5, 2, 7, 8, 4, 1],
             'all': [8, 5, 3, 1, 2]}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# initializing list
find_list = [7, 9, 2]
  
res = any(set(sub).issuperset(find_list) 
          for sub in test_dict.values())
  
# printing result
print("Is any value list superset ? : " + str(res))

输出: