如果您需要对值应用一些测试,这出现在关于迭代字典键的首选样式的挑剔讨论中。我正在比较[k for k in d if d[k] == 1]
反对的表现[k for k, v in d.items() if v == 1]
。
看起来字典查找在 Python 3.4 中更昂贵:
$ python -m timeit -n 1000000 \
-s 'd={k:v for v, k in enumerate("abcdefghijhklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")}' \
'[k for k in d if d[k] == 1]'
1000000 loops, best of 3: 2.17 usec per loop
$ python -m timeit -n 1000000 \
-s 'd={k:v for v, k in enumerate("abcdefghijhklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")}' \
'[k for k, v in d.items() if v == 1]'
1000000 loops, best of 3: 3.13 usec per loop
$ python3.4 -m timeit -n 1000000 \
-s 'd={k:v for v, k in enumerate("abcdefghijhklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")}' \
'[k for k in d if d[k] == 1]'
1000000 loops, best of 3: 3.25 usec per loop
$ python3.4 -m timeit -n 1000000 \
-s 'd={k:v for v, k in enumerate("abcdefghijhklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")}' \
'[k for k, v in d.items() if v == 1]'
1000000 loops, best of 3: 3.05 usec per loop
与 2.7 相比,Python 3.4 中的查找成本更高吗?您能解释一下原因吗?