【问题标题】:Python - find intersection of values in a dictPython - 在字典中查找值的交集
【发布时间】:2012-12-10 22:09:29
【问题描述】:

我正在编写一个函数来处理布尔 AND 搜索中的多个查询。 我有每个查询发生的文档字典= query_dict

我想要query_dict.values()中所有值的交集:

query_dict = {'foo': ['doc_one.txt', 'doc_two.txt', 'doc_three.txt'],
              'bar': ['doc_one.txt', 'doc_two.txt'],
              'foobar': ['doc_two.txt']}

intersect(query_dict)

>> doc_two.txt

我一直在阅读有关交集的内容,但我发现很难将其应用于字典。

感谢您的帮助!

【问题讨论】:

  • 它不是很清楚你到底想做什么......

标签: python dictionary intersection


【解决方案1】:
In [36]: query_dict = {'foo': ['doc_one.txt', 'doc_two.txt', 'doc_three.txt'],
              'bar': ['doc_one.txt', 'doc_two.txt'],
              'foobar': ['doc_two.txt']}

In [37]: reduce(set.intersection, (set(val) for val in query_dict.values()))
Out[37]: set(['doc_two.txt'])

在 [41] 中:query_dict = {'foo': ['doc_one.txt', 'doc_two.txt', 'doc_three.txt'], 'bar': ['doc_one.txt', 'doc_two.txt'], 'foobar': ['doc_two.txt']}

set.intersection(*(set(val) for val in query_dict.values())) 也是一个有效的解决方案,虽然它有点慢:

In [42]: %timeit reduce(set.intersection, (set(val) for val in query_dict.values()))
100000 loops, best of 3: 2.78 us per loop

In [43]: %timeit set.intersection(*(set(val) for val in query_dict.values()))
100000 loops, best of 3: 3.28 us per loop

【讨论】:

  • 代替reduceset.intersection(*(set(val).. etc)) 也应该可以工作。
  • @DSM:这也可以,但我的更快。查看我的更新答案
  • 如果您比较输入额外字符所需的时间,则不会,具体取决于您执行操作的次数。
  • reduce 在标准库中不再可用,请改用functools.reducestackoverflow.com/questions/8689184/…
【解决方案2】:

另一种方式

first = query_dict.values()[0]
rest = query_dict.values()[1:]
print [t for t in set(first) if all(t in q for q in rest)]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-12
    • 2014-07-03
    • 1970-01-01
    • 2020-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多