[英]Given a dictionary with lists of strings as their values, how would you retrieve all keys where the list contains a string unique to all other lists?
As an example if the dictionary was this:例如,如果字典是这样的:
myDict = {"egg sandwich":["bread", "lettuce", "mayo","egg"],
"sad sandwich":["bread","lettuce","mayo"],
"ham sandwich":["bread","lettuce","mayo","ham"],
"healthy sandwich":["lettuce"],
"breakfast sandwich":["bread","egg","mayo"]}
The function should return "ham sandwich" , since it is the only sandwich that contains an ingredient (ham) unique to a comparison of all other lists.该函数应返回“火腿三明治”,因为它是唯一包含与所有其他列表进行比较时所独有的成分(火腿)的三明治。
This seems to work:这似乎有效:
def get_unique_item(d):
all_ingredients = [y for x in d.values() for y in x]
output = []
for name, ingredients in d.items():
for ingredient in ingredients:
if all_ingredients.count(ingredient) == 1:
output.append(name)
break
return output
myDict = {"egg sandwich":["bread", "lettuce", "mayo","egg"],
"sad sandwich":["bread","lettuce","mayo"],
"ham sandwich":["bread","lettuce","mayo","ham"],
"healthy sandwich":["lettuce"],
"breakfast sandwich":["bread","egg","mayo"]}
print(get_unique_item(myDict))
Output:输出:
['ham sandwich']
Basically, we create a list of all occurrences of all ingredients, and for each sandwich, we check if there are any ingredients which only occur once.基本上,我们创建一个所有成分的所有出现的列表,对于每个三明治,我们检查是否有任何成分只出现一次。
If you really want to, you can make it a one-line list comprehension:如果你真的想,你可以把它变成一个单行列表理解:
[name for name, ingredients in d.items() if any([y for x in d.values() for y in set(x)].count(i) == 1 for i in ingredients)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.