以下是两种可能的替代方案:
import math
from functools import reduce
from collections import defaultdict
def map_keys_with(combine_f, op, mp):
ret = {}
for it in mp:
if op(it) in ret:
ret[op(it)] = combine_f(ret[op(it)], mp[it])
else:
ret[op(it)] = mp[it]
return ret
def map_keys_with_setdefault(combine_f, op, mp):
ret = {}
for key, value in mp.items():
ret.setdefault(op(key), []).append(value)
return {key: reduce(combine_f, values) for key, values in ret.items()}
def map_keys_with_defaultdict(combine_f, op, mp):
ret = defaultdict(list)
for key, value in mp.items():
ret[op(key)].append(value)
return {key: reduce(combine_f, values) for key, values in ret.items()}
z = {1: 2, 3: 4, 10: 11}
print(map_keys_with(lambda x, y: x + y, lambda x: math.floor(x / 10), z))
print(map_keys_with_setdefault(lambda x, y: x + y, lambda x: math.floor(x / 10), z))
print(map_keys_with_defaultdict(lambda x, y: x + y, lambda x: math.floor(x / 10), z))
输出
{0: 6, 1: 11}
{0: 6, 1: 11}
{0: 6, 1: 11}