Python – 常用列表元素和字典值
给定列表和字典,提取列表和字典值的共同元素。
Input : test_list = [“Gfg”, “is”, “Best”, “For”], subs_dict = {4 : “Gfg”, 8 : “Geeks”, 9 : ” Good”, }
Output : [‘Gfg’]
Explanation : “Gfg” is common in both list and dictionary value.
Input : test_list = [“Gfg”, “is”, “Best”, “For”, “Geeks”], subs_dict = {4 : “Gfg”, 8 : “Geeks”, 9 : ” Best”, }
Output : [‘Gfg’, “Geeks”, “Best”]
Explanation : 3 common values are extracted.
方法 #1:使用列表理解 + values()
上述功能的组合提供了一种可以在一行中执行此任务的方式。在此,我们使用 values() 提取字典的值,列表推导用于执行迭代和交叉检查。
Python3
# Python3 code to demonstrate working of
# List elements and dictionary values intersection
# Using list comprehension + values()
# initializing list
test_list = ["Gfg", "is", "Best", "For", "Geeks"]
# printing original list
print("The original list : " + str(test_list))
# initializing subs. Dictionary
subs_dict = {4 : "Gfg", 8 : "Geeks", 9 : " Good", }
# Intersection of elements, using "in" for checking presence
res = [ele for ele in test_list if ele in subs_dict.values()]
# printing result
print("Intersection elements : " + str(res))
Python3
# Python3 code to demonstrate working of
# Common list elements and dictionary values
# Using set() and intersection()
# initializing list
test_list = ["Gfg", "is", "Best", "For", "Geeks"]
# printing original list
print("The original list : " + str(test_list))
# initializing subs. Dictionary
subs_dict = {4 : "Gfg", 8 : "Geeks", 9 : " Good", }
# Intersection of elements, using set() to convert
# intersection() for common elements
res = list(set(test_list).intersection(list(subs_dict.values())))
# printing result
print("Intersection elements : " + str(res))
输出
The original list : ['Gfg', 'is', 'Best', 'For', 'Geeks']
Intersection elements : ['Gfg', 'Geeks']
方法#2:使用 set() + intersection()
在这种方法中,列表和字典值都被转换为 set(),然后执行交集以获得公共元素。
Python3
# Python3 code to demonstrate working of
# Common list elements and dictionary values
# Using set() and intersection()
# initializing list
test_list = ["Gfg", "is", "Best", "For", "Geeks"]
# printing original list
print("The original list : " + str(test_list))
# initializing subs. Dictionary
subs_dict = {4 : "Gfg", 8 : "Geeks", 9 : " Good", }
# Intersection of elements, using set() to convert
# intersection() for common elements
res = list(set(test_list).intersection(list(subs_dict.values())))
# printing result
print("Intersection elements : " + str(res))
输出
The original list : ['Gfg', 'is', 'Best', 'For', 'Geeks']
Intersection elements : ['Geeks', 'Gfg']