python - 给定一个以字符串列表为值的字典,您将如何检索列表中包含对所有其他列表唯一的字符串的所有键?
问题描述
例如,如果字典是这样的:
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"]}
该函数应返回“火腿三明治”,因为它是唯一包含与所有其他列表进行比较的成分(火腿)的三明治。
解决方案
这似乎有效:
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)]
推荐阅读
- c# - 使用 .net core 3.0 进行脚本动态编译和运行代码
- powerbi - DAX 模拟不同 X 变量值的结果
- java - switch 语句中的中断是否会终止 for 循环?
- python - 如何根据其他数据框计算数据框中的缺失值
- swift - Swift 中的按钮不可点击
- ruby - 将缺少的括号添加到给定的字符串
- angular - 为什么我在 Angular 中的不记名令牌在 Firefox 中不可见
- c++ - C++:Lambda 到函数指针转换的用例是什么?
- javascript - 我怎么知道 Summernote(富文本编辑器)是专注的?
- mongodb - MongoDB Collection,使用终端命令对所有键值求和