希望有人能提出一种简单的方法来以非常具体的方式搜索大嵌套字典。
字典示例:
foo = {"item1" : ((0.1, 0.03 , 0.7), (0.01, 0.01, 0.02), (0.3, 0.4, 0.05)), "item2" : ((0.5, 0.2 , 0.01), (0.1, 0.3, 1.0), (0.4, 0.2, 0.8))}
我想使用两个约束来搜索上面的内容。元组的位置以及要搜索并返回任何匹配结果的范围及其在列表中的索引位置及其相应的字典键,其中键值是真实索引位置的列表。
示例:使用范围 (0.7-1.0) 搜索元组的位置 2,我想要返回一个字典:
{"item1" : (0), "item2" : (1, 2)}
我不确定如何使用约束运行搜索并按照我想要的方式格式化结果。有什么建议会很棒吗?非常感谢。
最佳答案
您可以定义自己的函数:
def special_search(my_dict, pos, min, max):
result = {}
for item, tuples in my_dict.items():
matches = []
for i, t in enumerate(tuples):
if min <= t[pos] <= max:
matches.append(i)
if matches:
result[item] = tuple(matches)
return result
使用您的示例:
>>> foo = {"item1": ((0.1, 0.03 , 0.7), (0.01, 0.01, 0.02), (0.3, 0.4, 0.05)),
... "item2": ((0.5, 0.2 , 0.01), (0.1, 0.3, 1.0), (0.4, 0.2, 0.8))}
>>> special_search(foo, 2, 0.7, 1.0)
{'item2': (1, 2), 'item1': (0,)}
关于python - 如何在考虑到特定约束的情况下搜索嵌套字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9118739/