這一個是推廣到http://stardict.sourceforge.net/Dictionaries.php下載任意數量的,可以應用到列表中的所有功能,並http://stardict.sourceforge.net/Dictionaries.php下載使用不同的密鑰:
def agg_dicts(func, *args):
keys = []
for d in args:
keys += list(d.keys())
keys = set(keys)
out = {}
for key in keys:
vals = [d[key] for d in args if key in d.keys()]
out[key] = func(vals)
return out
from numpy import mean
a = {'one':1, 'two':4, 'four':2}
b = {'one':2, 'two':2}
c = {'two':4, 'four':2, 'five':5}
dict_min = agg_dicts(min, a, b, c)
dict_max = agg_dicts(max, a, b)
dict_avg = agg_dicts(mean, a, b, c)
dict_sum = agg_dicts(sum, a, b, c)
dict_max
{'four': 2, 'one': 2, 'two': 4}
dict_min
{'five': 5, 'four': 2, 'one': 1, 'two': 2}
dict_max
{'four': 2, 'one': 2, 'two': 4}
dict_avg
{'five': 5.0, 'four': 2.0, 'one': 1.5, 'two': 3.3333333333333335}
dict_sum
{'five': 5, 'four': 4, 'one': 3, 'two': 10}
這是我不清楚什麼約束 - 例如,在你的max_dict實現中,d2中的額外鍵將被忽略,儘管這在文檔中沒有指定。如果類型不對齊,你想要豁免嗎(「帽子」+3等)?我懷疑是否有內建功能來做你想做的事情,因爲這些問題的答案將是特定於案例的 –
@en_Knight:上面是一個應該小心處理的示例實現。如果要在圖書館中實施,如果僅存在一個值,並且如果存在多個值,則應用操作會很酷。這應該相當於'list'的'max'等功能。 –