GIS之时空数据分析

Python实现字典一个键对应多个值

2019-07-21  本文已影响0人  王叽叽的小心情

Python实现字典的一键多值情况,采用 { key: [list] }形式;并根据键对多个值进行平均。

可复制代码:

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)

# 对字典的一个键对应的多个值进行平均,存储在两个数组中

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)

输出结果:

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]

上一篇下一篇

猜你喜欢

热点阅读