Answers:
len()
直接在您的字典上进行调用是有效的,并且比构建迭代器,d.keys()
和对其进行调用要快len()
,但是与您的程序正在执行的其他操作相比,两者的速度都可以忽略不计。
d = {x: x**2 for x in range(1000)}
len(d)
# 1000
len(d.keys())
# 1000
%timeit len(d)
# 41.9 ns ± 0.244 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
%timeit len(d.keys())
# 83.3 ns ± 0.41 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
如果问题是关于计算关键字数量,则建议使用类似
def countoccurrences(store, value):
try:
store[value] = store[value] + 1
except KeyError as e:
store[value] = 1
return
在main函数中有一些循环数据并将值传递给countoccurrences函数的东西
if __name__ == "__main__":
store = {}
list = ('a', 'a', 'b', 'c', 'c')
for data in list:
countoccurrences(store, data)
for k, v in store.iteritems():
print "Key " + k + " has occurred " + str(v) + " times"
代码输出
Key a has occurred 2 times
Key c has occurred 2 times
Key b has occurred 1 times
countoccurrences()
应改为count_occurrences()
。另外,如果导入collections.Counter
,还有一个更好的方法来做到这一点:from collections import Counter; store = Counter(); for data in list: store[list] += 1
。
在发布的答案UnderWaterKremlin上进行了一些修改,以使其成为python3证明。下面是一个令人惊讶的结果作为答案。
系统规格:
import timeit
d = {x: x**2 for x in range(1000)}
#print (d)
print (len(d))
# 1000
print (len(d.keys()))
# 1000
print (timeit.timeit('len({x: x**2 for x in range(1000)})', number=100000)) # 1
print (timeit.timeit('len({x: x**2 for x in range(1000)}.keys())', number=100000)) # 2
结果:
1)= 37.0100378
2)= 37.002148899999995
因此,len(d.keys())
目前看来比使用来得快len()
。