检查list_1中的元素是否与dict.key匹配,list_2中的元素与dict.value匹配



我有两个列表和一个字典:

list_1 = ['the world', 'abc', 'bcd', 'want a car', 'hell', 'you rock']
list_2 = ['the world is big', 'i want a car', 'puppies are best', 'you rock the world']
dict_1 = {'a car':'i want a car', 'champ':'i am champ', 'you know':'you rock the world'}

现在,我想检查来自dict_1的键是否部分地匹配来自list_1的元素,同时如果来自dict_1部分地的值匹配来自list_2的元素,那么它是有效的匹配,我们必须打印来自list_1的匹配元素。

例如:

dict_1.key('a car') matches 'want a car' from list_1

同时

dict_1.value('i want') matches 'i want a car' from list_2

因此,这成为一个有效的匹配。

到目前为止我尝试过的:

out = [ele_1 for key, value in dict_1.iteritems() for ele_1 in list_1 if key in ele_1 for elem_2 in list_2 if value in elem_2]
print list(set(out))

此打印:

['want a car']

但我不相信这是我所采取的最好的方法,我想了解我是否能提高自己的技能。

这个答案可能会帮助您

#Let there are two list list1 and list2 and a dictonary dict
list1=[2,5,6]
list2=[3,4,5]
dict={}
dict[2]=5
dict[3]=4
#The below given code checks whether the element from list1 matches dict.key and if it matches it will print "Key is present" else "Key is not present"
if dict.get(2)!=None:
print("Key is present")
else:
print("Key is not present")
#The below given code checks whether the element from list2 matches dict.value and if it matches it will print "Item is present" else "Item is not present"
if 4 in dict.values():
print("Item is present in dict.values")
else:
print("Item is not present in dict.values")

最新更新