我支持我的建議,使用def_dict[k] = [v]
會比def_dict[k].append(v)
更快,基於我自己的測試,發現它幾乎快兩倍。
以下是我用來確定這一點的完整代號。我也嘗試了其他一些可能性,但沒有一個更好。
Python 3.5.0和Python 2.7.10都獲得了類似的結果。
from __future__ import print_function
import sys
from textwrap import dedent
import timeit
N = 1000000 # number of executions of each "algorithm"
R = 3 # number of Repeations of executions
# common setup for all algorithms (not timed)
setup = dedent("""
from collections import defaultdict
new_dict = {'a': 1, 'b': 2, 'c': 3, 'e': 4, 'f': 5}
""")
algorithms = {
"def_dict[k].append(v)": dedent("""
def_dict = defaultdict(list)
for k, v in new_dict.items(): def_dict[k].append(v)
"""),
"def_dict[k] = [v]": dedent("""
def_dict = defaultdict(list)
for k, v in new_dict.items(): def_dict[k] = [v]
"""),
"defaultdict(list, <gen-xprsn>)": dedent("""
def_dict = defaultdict(list, ((k, [v]) for k, v in new_dict.items()))
"""),
"defaultdict(list, <dict-comp>)": dedent("""
def_dict = defaultdict(list, {k:[v] for k, v in new_dict.items()})
"""),
}
# collecting results of executing and timing each algorithm snippet
timings = [
(label,
min(timeit.repeat(algorithms[label], setup=setup, repeat=R, number=N)),
) for label in algorithms
]
# display results
print('fastest to slowest execution speeds (Python {}.{}.{})\n'.format(
*sys.version_info[:3]),
' ({:,d} executions, best of {:d} repetitions)\n'.format(N, R))
longest = max(len(timing[0]) for timing in timings) # length of longest label
ranked = sorted(timings, key=lambda t: t[1]) # ascending sort by execution time
fastest = ranked[0][1]
for timing in ranked:
print("{:>{width}} : {:9.6f} secs, rel speed {:4.2f}x, {:6.2f}% slower".
format(timing[0], timing[1], round(timing[1]/fastest, 2),
round((timing[1]/fastest - 1) * 100, 2), width=longest))
這裏是我的系統上運行的結果:
fastest to slowest execution speeds (Python 3.5.0)
(1,000,000 executions, best of 3 repetitions)
def_dict[k] = [v] : 0.977644 secs, rel speed 1.00x, 0.00% slower
defaultdict(list, <dict-comp>) : 1.330040 secs, rel speed 1.36x, 36.05% slower
defaultdict(list, <gen-xprsn>) : 1.761532 secs, rel speed 1.80x, 80.18% slower
def_dict[k].append(v) : 1.929081 secs, rel speed 1.97x, 97.32% slower
你怎麼知道時的表現也不夠好? –
@PeterWood通過性能,我的意思是運行該功能所需的時間。 –
優化爲了什麼目的? – morels