亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

給定一個以字符串列表作為其值的字典,您將如何檢索該列表包含所有其他列表唯一字符串的所有鍵?

給定一個以字符串列表作為其值的字典,您將如何檢索該列表包含所有其他列表唯一字符串的所有鍵?

蝴蝶刀刀 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 關注
  • 127 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號