gpt4 book ai didi

python - 优化从大型字典中检索值

转载 作者:行者123 更新时间:2023-11-28 22:21:15 25 4
gpt4 key购买 nike

我有一本字典 id_to_phone。它包含大约 350,000 个唯一 ID(字典键),每个 ID 代表唯一电话号码(字典值)。我的要求是获取我的代码生成的 ID 的电话号码。从我的代码中生成了大约 10,000 到 50,000 个 ID,并从我的 ID需要找到匹配的电话号码并将其存储在数组中。我使用了以下代码

count=phone_id.shape[0]
phone_array=np.array([])
for i in range(count):
phone=id_to_phone[phone_id[i]]
phone_array=np.append(phone_array,phone)

但是这段代码耗时很长,有什么办法可以优化我的代码吗?

最佳答案

你的问题不是字典查找,而是 np.append。 NumPy 数组是固定大小的连续内存块, 追加到它们,超出当前大小,需要重新调整整个内存块的大小并移动(复制到其他地方),这需要很长时间,如果你只是做了一些追加没关系,但是做很多追加可能会增加数组的大小,超出最初分配的大小。 (更正)来自 docs :

Return: A copy of arr with values appended to axis. Note that append does not occur in-place: a new array is allocated and filled. If axis is None, out is a flattened array.

所以 每次 调用 np.append 都会复制数组,难怪要花很长时间。

改用常规的 python 列表,附加到列表的时间是恒定的。

import timeit

import numpy as np

def np_append():
arr = np.asarray([])
for i in range(5000):
np.append(arr, i)

def list_append():
ls = []
for i in range(5000):
ls.append(i)

if __name__ == "__main__":
print(timeit.repeat('np_append()', number=10, repeat=3, globals=globals()))
print(timeit.repeat('list_append()', number=10, repeat=3, globals=globals()))

时间安排如下

np_append : [0.15639284392818809, 0.15938732610084116, 0.15667122812010348]
list_append : [0.003160736057907343, 0.004024225985631347, 0.003376785898581147]

或者,如果您知道要添加到列表中的元素数量,您可以使用 phone_array = np.zeros((15000 , 10)),例如,对于 15000 个 10 位电话号码。

关于python - 优化从大型字典中检索值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48458485/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com