【问题标题】: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?给定一个以字符串列表为值的字典,您将如何检索列表中包含对所有其他列表唯一的字符串的所有键?
【发布时间】:2020-03-03 21:29:58
【问题描述】:

例如,如果字典是这样的:

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"]}

该函数应返回“火腿三明治”,因为它是唯一一个包含与所有其他列表进行比较时唯一的成分(火腿)的三明治。

【问题讨论】:

  • “健康三明治”也应该回归吧?
  • @GUNTERSAMA 为什么?前三个三明治也包含“生菜”。
  • @GUNTERSAMA,约翰·戈登是正确的。该函数应该只返回包含对所有其他列表唯一的值的键。
  • 是的,我看错了。

标签: python list dictionary optimization


【解决方案1】:

这似乎有效:

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

【讨论】:

  • 这是一个快速的解决方案吗?我正在使用的字典有大约 100,000 个项目,列表包含 10 到 40 个元素。
  • 我真的不知道 - 我想先用 100 测试它,然后可能是 1000,等等......在这种情况下不要使用列表 comp :)
猜你喜欢
  • 2012-12-03
  • 2019-07-21
  • 1970-01-01
  • 2021-12-31
  • 1970-01-01
  • 2015-04-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多