【问题标题】:python fatest way to iterate compare two dictionary valuespython最快的迭代方法比较两个字典值
【发布时间】:2017-07-11 13:10:13
【问题描述】:

我有两本词典

user_hash = {
"as34": "98354897394053452345",
"ad23" : "2131313111313131313",
"ae23": "31245512121521212121"
}


 active_user_hash =  [
   {"field0": "231634684712313"}, 
   {"field0" : "23145454564120"}, 
   {"field0" : "215465464133313"}]

实际上,这些字典和字典列表中有数百万个键值对。目的是遍历字典 1 的每个值,并使用自定义函数将其与字典值的第二个列表进行比较。我不能对这个逻辑使用任何类型的排序或优化,因为每个元素到元素的比较都是必要的。最快的方法是什么?

当前循环需要 11 分钟!我想把它减少到几秒钟。

    for index, id_hash in user_hash.iteritems():
        try:
            for element in active_user_hash:

                match = custom_comparison_function_algo(id_hash, element['field0'])
                if match < 40:
                    print 'success'

        except Exception as err:
            print err

import distance

def custom_comparison_function_algo(hash1, hash2):

    levenshtein_dist = distance.nlevenshtein(hash1, hash2, method=1)
    jaccard_dist = distance.jaccard(hash1, hash2)
    return int(((levenshtein_dist + jaccard_dist) / 2) * 100)

我尝试过 numpy 矢量化,但无法理解它。

【问题讨论】:

  • 如何从values 构造sets,得到它们的交点,最后逆向查找keys
  • 成功矢量化的可能性完全取决于 custom_comparison_function_algo 的内部结构
  • 所有的哈希值都是唯一的。 custom_comparison_function_algo 使用距离 python 库。我想得到比赛和钥匙。
  • 我不确定是否有任何明智的方法来解决这个问题。如果您有n 哈希和m 比较对象并进行Levenstein 和Jaccard 距离(它们的运行时间取决于字符串长度,例如k),您最终会得到n*m*k 运行时间。 nm 的数量级为数百万,字符串长度为 20,您最终将进行数十万亿次操作...
  • 为什么要对哈希进行距离匹配?散列的重点是避免这种情况......

标签: python python-2.7 numpy ipython


【解决方案1】:

如果您从 active_user_hash 字典的值创建一个列表(或 Ev. Kounis 建议的一个集合),然后在列表理解中运行您的函数会怎样?

  search_in = [ x.values()[0] for x in active_user_hash ]
  res = [ x in search_in for x in user_hash.values() ]

【讨论】:

    猜你喜欢
    • 2018-01-25
    • 1970-01-01
    • 2016-11-12
    • 1970-01-01
    • 2017-09-04
    • 1970-01-01
    • 1970-01-01
    • 2019-12-03
    • 1970-01-01
    相关资源
    最近更新 更多