为了账号安全,请及时绑定邮箱和手机立即绑定

给定一个以字符串列表作为其值的字典,您将如何检索该列表包含所有其他列表唯一字符串的所有键?

给定一个以字符串列表作为其值的字典,您将如何检索该列表包含所有其他列表唯一字符串的所有键?

蝴蝶刀刀 2022-08-16 16:36:20
举个例子,如果字典是这样的: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"]}该函数应返回“火腿三明治”,因为它是唯一包含所有其他列表比较所特有的成分(火腿)的三明治。
查看完整描述

1 回答

?
桃花长相依

TA贡献1860条经验 获得超8个赞

这似乎有效:


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']

基本上,我们创建了所有成分的所有出现的列表,对于每个三明治,我们检查是否有任何成分只出现一次。


如果你真的想,你可以把它变成一行列表理解:


[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)]



查看完整回答
反对 回复 2022-08-16
  • 1 回答
  • 0 关注
  • 95 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信