2 回答
TA贡献1846条经验 获得超7个赞
如果您可以将所有内容存储在numpy数组中,则处理速度会更快。我将每个列表的大小增加了 50 万倍以测试可伸缩性,以下是我的结果:
from timeit import timeit
import numpy as np
n = 500000
example_dict1 = {'key1':[367, 30, 847, 482, 887, 654, 347, 504, 413, 821]*n,
'key2':[754, 915, 622, 149, 279, 192, 312, 203, 742, 846]*n,
'key3':[586, 521, 470, 476, 693, 426, 746, 733, 528, 565]*n}
def manipulate_values(input_list):
return_values = []
for i in input_list:
new_value = i ** 2 - 13
return_values.append(new_value)
return return_values
使用您的方法:
for_with_dictionary = timeit("""
for key, value in example_dict1.items():
example_dict1[key] = manipulate_values(value)
""", "from __main__ import example_dict1,manipulate_values ",number=5)
print(for_with_dictionary)
>>> 33.2095841
使用 numpy:
numpy_broadcasting = timeit("""
array = np.array(list(example_dict1.values()))
array = array ** 2 - 13
""", "from __main__ import example_dict1, np",number=5)
print(numpy_broadcasting)
>>> 5.039885
速度有显着提升,至少6倍。
TA贡献1860条经验 获得超8个赞
如果您有足够的内存:
example_dict2 = dict(zip(example_dict1.keys(), np.array(list(example_dict1.values()))**2 -13))
>>> example_dict2
{'key1': array([134676, 887, 717396, 232311, 786756, 427703, 120396, 254003,
170556, 674028]), 'key2': array([568503, 837212, 386871, 22188, 77828, 36851, 97331, 41196,
550551, 715703]), 'key3': array([343383, 271428, 220887, 226563, 480236, 181463, 556503, 537276,
278771, 319212])}
添加回答
举报