2012-02-02 13 views
1

希望有人可以建议一种简单的方法来以一种非常特定的方式搜索大型嵌套字典。所述字典的我怎样才能搜索一个嵌套的字典与特定的约束记住

实施例:

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

我不确定如何使用约束来运行搜索和格式化回结果我想要的方式。任何建议会很好?非常感谢。

+0

向我们展示您的预期方法的一些代码。 – Marcin 2012-02-02 19:37:47

+0

嗨Marcin(感谢您清理我的文章)。我还没有办法,我正在努力解决如何解决这个问题。我在看例如:过滤器(lambda号码:,[1,2,3,4,5,6,7,8,9,10]),但它是我有问题的应用程序。如果复杂化搜索的话,我可能需要重新思考我的Dic,以使它更容易。 – nick 2012-02-02 19:45:57

+0

我不得不说,我已经找到了你想要做的很不透明的描述。 – Marcin 2012-02-02 19:56:42

回答

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,)} 
+0

嗨Julio!谢谢,非常有帮助。我相当新的python和这个版本,我可以阅读最简单的...感谢所有的建议。干杯 – nick 2012-02-03 18:11:26

1

您也可以使用函数自定义测试:

from operator import itemgetter 

test = lambda t: 0.7 <= itemgetter(2)(t) <= 1.0 
results = dict((k, tuple(n for n,v in enumerate(t) if test(v))) for k,t in foo.items()) 

print(results) 
# {'item2': (1, 2), 'item1': (0,)} 
+0

我喜欢单独的列表理解比其他的东西更好,我有'字典((关键,元组(索引索引,smalltup在枚举(bigtup)如果my_range [0] <= smalltup [my_index] <= my_range [1 ]))key,bigtup在foo.items())''但测试函数很好 – steabert 2012-02-02 20:50:38

0

更短,更快执行julio.alegria的(+1)算法:

def search(d, pos, min, max): 
    searchspace = set(range(min(max)) 
    answer = {} 
    for k, v in d.iteritems(): 
     answer[k] = tuple([i for i,tuple in enumerate(v) if tuple[pos] in searchspace]) 
    return dict(((k, d[k]) for k in in d if d[k])) 
相关问题