2012-02-02 14 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])) 
相關問題