【问题标题】:How can I search a nested dictionary with specific constraints in mind如何搜索具有特定约束的嵌套字典
【发布时间】:2012-02-25 11:39:37
【问题描述】:

希望有人可以提出一种简单的方法来以非常具体的方式搜索大型嵌套字典。

字典示例:

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

我想使用两个约束来搜索上面的内容。元组的位置和要搜索的范围,并返回任何匹配结果及其在列表中的索引位置及其对应的 dict 键,其中键值是真实索引位置的列表。

示例:使用 (0.7-1.0) 的范围搜索元组的位置 2,我想要一个 dict 返回:

{"item1" : (0), "item2" : (1, 2)}

我不确定如何使用约束运行搜索并按照我想要的方式格式化结果。有什么建议会很棒吗?非常感谢。

【问题讨论】:

  • 向我们展示一些您想要的方法的代码。
  • 嗨,Marcin(感谢您清理我的帖子)。我还没有办法,我正在努力弄清楚如何去做。例如,我正在查看: filter(lambda number: , [1,2,3,4,5,6,7,8,9,10]) 但这是我遇到问题的应用程序。如果搜索变得复杂,我可能需要重新考虑我的 Dic 以使其更容易。
  • 我不得不说,我发现你对你想做的事情的描述非常不透明。

标签: python search dictionary


【解决方案1】:

你可以定义你自己的函数:

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相当陌生,这个版本我可以阅读最简单的......谢谢大家的建议。干杯
【解决方案2】:

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

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

【讨论】:

  • 我比其他东西更喜欢单个列表理解,我有 dict( (key,tuple(index for index,smalltup in enumerate(bigtup) if my_range[0] &lt;= smalltup[my_index] &lt;= my_range[1])) for key,bigtup in foo.items() ) 但测试功能很好
【解决方案3】:

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

【讨论】:

    猜你喜欢
    • 2020-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-14
    • 1970-01-01
    相关资源
    最近更新 更多