簡體   English   中英

檢查 list_1 中的元素是否匹配 dict.key 和 list_2 中的元素是否匹配 dict.value

[英]Check if element from list_1 matches dict.key and element from list_2 matches 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")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM