[英]generate list of dictionaries from template dictionary and keys
我正在尝试使一系列测试自动化,并且需要有一个循环来更改参数。
mydictionary={'a':10,'b':100,'c':30}
def swapRules(d,rule):
"clear dict, set to 100 the rule that match the string"
print d, rule
if not d.has_key(rule): raise Exception("wrong string")
d=resetDict(d)
d[rule]=100
return d
def resetDict(d):
'''clear the dict '''
for i in d.keys():
d[i]=0
return d
def tests(d):
from itertools import starmap, repeat, izip
keys=d.keys()
paramsDictionaries=list(starmap(swapRules, izip(repeat(d),keys)))
print(paramsDictionaries)
我不明白为什么当我运行test(mydictionary)时输出总是包含相同的值。 似乎问题不在于对itertools的错误使用:如REPL所示,用简单的列表理解代替:
In [9]: keys=mydictionary.keys()
In [10]: [tr.swapRules(mydictionary,jj) for jj in keys]
{'a': 0, 'c': 0, 'b': 100} a
{'a': 100, 'c': 0, 'b': 0} c
{'a': 0, 'c': 100, 'b': 0} b
Out[10]:
[{'a': 0, 'b': 100, 'c': 0},
{'a': 0, 'b': 100, 'c': 0},
{'a': 0, 'b': 100, 'c': 0}]
我真的感到很困惑,因为当单独调用swapRules函数时,会产生预期的结果,如print语句所示...对我做错的事情有任何想法吗? 是不是偶然缓存了一些东西?
自从发现这项工作以来,回答我自己的问题:
def swapRules2(d,rule):
'''clear dict, return new with only rule set'''
keys=d.keys()
if rule not in keys: raise Exception("wrong key")
outd=dict.fromkeys(keys,0)
outd[rule]=100
return outd
并在列表理解中返回预期的输出:
In [16]: [tr.swapRules2(mydict,jj) for jj in keys]
Out[16]:
[{'a': 100, 'b': 0, 'c': 0},
{'a': 0, 'b': 0, 'c': 100},
{'a': 0, 'b': 100, 'c': 0}]
但是,我仍然不明白为什么以前的方法没有。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.