1

我正在尝试自动化一系列测试,我需要有一个循环来更改参数。

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 语句所示......知道我做错了什么吗?有没有机会缓存​​一些东西?

4

1 回答 1

0

回答我自己的问题,因为我发现这项工作:

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}]

但是,我仍然不明白为什么以前的方法没有。

于 2013-07-11T18:52:32.473 回答