【问题标题】:Faster way to access a dictionary of lists?访问列表字典的更快方法?
【发布时间】:2020-12-14 02:31:05
【问题描述】:

我正在尝试找到一种快速访问 defaultdict(list) 的方法。我目前的代码如下:

import math

index = {str:[(id, int), (id, int)]}

def myfunc(docID, index):
    x = 0
    for str, tuple in index.items():
        for item in tuple:
            if item[0] == docID:
                x += entry[1] ** 2
    result = math.sqrt(sumOfItems)
    return result

任务是比较两个数字,如果它们匹配,则继续。 一个数字(docID)被传递给函数,另一个数字存储在字典内列表内的元组中。目标是尽可能快地遍历字典中的列表。

我以不同方式存储数据(即以较少嵌套的方式)的选择是有限的,但如果这是关键的区别,我需要重新考虑存储过程。

提前感谢任何提示、改进、建议等!

【问题讨论】:

    标签: python performance dictionary for-loop nested


    【解决方案1】:

    如果你稍微改变一下你的存储选项,你会获得很大的优势:

    index = {
        str: {
          id: [int, int, int],
          id: [int, int, int]
      },
        str: {
          id: [int, int, int],
          id: [int, int, int]
      },
        str: {
          id: [int, int, int],
          id: [int, int, int]
      }
    }
    

    这样你需要遍历第一级键,然后简单地累加x+= sum(index[key][id])

    这里的重要时刻是每个内部字典都必须是默认字典,否则如果您尝试访问缺少的键,您将得到一个错误

    【讨论】:

    • 所以如果我使用该方法并且当前 id 不存在,我必须让循环继续,对吗?还是会自动执行?
    【解决方案2】:

    您最好的方法是将 dict 值转换为列表以方便地对其进行切片,这是我的几行但快速的方法

    ind = {"str": [("elem", 33), ("elem", 77)]}
    
    x = list(ind.values())
    
    print(x[0][0][1], x[0][1][1])
    

    输出

    33 77
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-12
      • 2015-10-31
      相关资源
      最近更新 更多