Python實(shí)現(xiàn)字典的一鍵多值情況,采用 { key: [list] }形式删铃;并根據(jù)鍵對(duì)多個(gè)值進(jìn)行平均耳贬。
可復(fù)制代碼:
keys = [1,2,3,4,5,6,3,4,5,7]
values = [11,22,33,44,55,66,77,88,99,100]
dictionary = {}
for i in range(len(keys)):
? ? dictionary.setdefault(keys[i], []).append(values[i])
print('Dictionary: %s' %dictionary)
# 對(duì)字典的一個(gè)鍵對(duì)應(yīng)的多個(gè)值進(jìn)行平均,存儲(chǔ)在兩個(gè)數(shù)組中
import numpy as np
key = []
value_avg = []
for k, v in dictionary.items():
? ? key.append(k)
? ? if len(v) >1 :
? ? ? ? value_avg.append(np.mean(np.array(v)))
? ? else:
? ? ? ? value_avg.append(v[0])
print('The key array is : %s' % key)
print('Averaged value is: %s' % value_avg)
輸出結(jié)果:
Dictionary: {1: [11], 2: [22], 3: [33, 77], 4: [44, 88], 5: [55, 99], 6: [66], 7: [100]}
The key array is : [1, 2, 3, 4, 5, 6, 7]
Averaged value is: [11, 22, 55.0, 66.0, 77.0, 66, 100]