首先,我是Python的新手,所以如果我忽略了某些内容,我会道歉,但我想使用dict.fromkeys
(或类似的东西)来创建列表字典,其中的键在另一个列表中提供.我正在执行一些计时测试,我希望键是输入变量,列表包含运行的时间:
def benchmark(input): ... return time_taken runs = 10 inputs = (1, 2, 3, 5, 8, 13, 21, 34, 55) results = dict.fromkeys(inputs, []) for run in range(0, runs): for i in inputs: results[i].append(benchmark(i))
我遇到的问题是字典中的所有键似乎共享相同的列表,每次运行只是附加到它.有没有办法为每个密钥生成一个唯一的空列表fromkeys
?如果没有,是否有其他方法可以手动生成结果字典?
查看defaultdict(需要Python 2.5或更高版本).
from collections import defaultdict def benchmark(input): ... return time_taken runs = 10 inputs = (1, 2, 3, 5, 8, 13, 21, 34, 55) results = defaultdict(list) # Creates a dict where the default value for any key is an empty list for run in range(0, runs): for i in inputs: results[i].append(benchmark(i))
问题在于
results = dict.fromkeys(inputs, [])
[]只评估一次,就在那里.
我会像这样重写这段代码:
runs = 10 inputs = (1, 2, 3, 5, 8, 13, 21, 34, 55) results = {} for run in range(runs): for i in inputs: results.setdefault(i,[]).append(benchmark(i))
其他选择是:
runs = 10 inputs = (1, 2, 3, 5, 8, 13, 21, 34, 55) results = dict([(i,[]) for i in inputs]) for run in range(runs): for i in inputs: results[i].append(benchmark(i))