【发布时间】:2021-03-04 04:53:23
【问题描述】:
我使用字典和列表进行了几次测试,以比较访问速度。除了 100 个项目在所有其他场景中(有更多项目)的情况外,字典访问比列表索引访问快。这背后的原因是什么?我能想到的唯一原因是字典初始化时分配了大内存和内存有限的列表,以及当项目数量增加时在列表上花费的复制时间。以下是我用于测试的代码:
a = np.random.rand(1000000, 15)
large_list_of_lists = a.tolist()
keys = list('abcdefghijklmno')
large_list_of_dicts = [dict(zip(keys, values)) for values in large_list_of_lists]
def test_large_list_of_lists():
list_total = 0
for list_row in large_list_of_lists:
for i in range(15):
list_total += list_row[i]
print(f'List total: {list_total}')
def test_large_list_of_dicts():
dict_total = 0
for dict_row in large_list_of_dicts:
for k in keys:
dict_total += dict_row[k]
print(f'Dict total: {dict_total}')
def timef(func):
start_time = time.time()
func()
print(f'Time: {time.time()-start_time}')
for f in [test_large_list_of_lists, test_large_list_of_dicts]:
timef(f)
List total: 7498408.687142285
Time: 0.9701709747314453
Dict total: 7498408.687142285
Time: 0.6495280265808105
【问题讨论】:
-
什么时候用
pass替换+=行?最好不要在基准测试中包含prints。timef在哪里?
标签: python python-3.x list dictionary