def sum_specified_dims(mdd, dims, keys = [], result = {}):
for key,value in mdd.items():
keys.append(key)
if type(value) == dict:
sum_specified_dims(value, dims, keys, result)
else:
pointer = result
for dim in dims:
index = dim - 1
key_value = keys[index]
if not key_value in pointer:
pointer[key_value] = {}
pointer = pointer[key_value]
if key_of_sum in pointer:
pointer[key_of_sum] += value
else:
pointer[key_of_sum] = value
keys.pop()
return result
key_of_sum='total'
keys=[1]
import datetime
mdd={datetime.date(2013, 7, 16): {3.0: {'2.0': 8}}}
>>> sum_specified_dims(mdd,keys)
{datetime.date(2013, 7, 16): {'total': 8}}
>>> sum_specified_dims(mdd,keys)
{datetime.date(2013, 7, 16): {'total': 16}}
>>> sum_specified_dims(mdd,keys,[],{})
{datetime.date(2013, 7, 16): {'total': 8}}
如果我省略了第 3、4 个参数,结果每次都会累加。
但是如果我不省略任何参数就可以了。
任何人都可以解释为什么会发生这种情况,它是一个 python 错误吗?
更新
它似乎并不总是发生:
>>> def f(a=2):
... print a
...
>>> f(3)
3
>>> f()
2