1 回答

TA貢獻(xiàn)1860條經(jīng)驗(yàn) 獲得超8個(gè)贊
這似乎有效:
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))
輸出:
['ham sandwich']
基本上,我們創(chuàng)建了所有成分的所有出現(xiàn)的列表,對于每個(gè)三明治,我們檢查是否有任何成分只出現(xiàn)一次。
如果你真的想,你可以把它變成一行列表理解:
[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)]
添加回答
舉報(bào)