如果不需要搜索,请使用列表。它比dict更快,占用的内存更少。对于小型收集(100个项目),速度差异最小,但对于大型收集,dict将慢20%左右。它肯定会使用更多的内存。在
下面是一些比较list和dict访问速度的timeit代码。它还显示了收集对象本身(但不是它们所保存的数据对象的RAM)消耗的RAM。在#!/usr/bin/env python3
''' Compare list vs dict access speed
See http://stackoverflow.com/q/39192442/4014959
Written by PM 2Ring 2016.08.29
'''
from sys import getsizeof
from timeit import Timer
commands = {'dict' : 'for i in r:d[i]', 'list' : 'for i in r:a[i]'}
def time_test(loops, reps):
timings = []
setup = 'from __main__ import r, a, d'
for name, cmd in commands.items():
result = Timer(cmd, setup).repeat(reps, loops)
result.sort()
timings.append((result, name))
timings.sort()
for result, name in timings:
print(name, result)
#Find the ratio of slowest / fastest
tlo, thi = [timings[i][0][0] for i in (0, -1)]
print('ratio: {0:f}\n'.format(thi / tlo))
num = 2000
r = range(num)
a = list(r)
d = {i:i for i in r}
fmt = 'Sizes: num={}, list={}, dict={}'
print(fmt.format(num, getsizeof(a), getsizeof(d)))
loops, reps = 2000, 3
time_test(loops, reps)
输出
^{pr2}$
速度差实际上比这些结果中显示的要高,因为从r范围对象检索整数所用的时间与执行list&dict访问所用的时间大致相同。您可以通过在commands字典中添加这样一个条目来度量:'none': 'for i in r:i'