简体   繁体   中英

Replace dictionary value list with average

I have a dictionary, say mydict , like this:

key1: list1
key2: list2
key3: list3

what is the pythonic way of replacing the lists (values) with their averages (avoiding for loops)?

In Python 3 you can import mean from statistics and use a dictionary comprehension:

>>> from statistics import mean
>>> d = {'a':[1,2,3],'b':[4,5,6],'c':[7,8,9]}
>>> d = {k:mean(v) for k,v in d.items()}
>>> d
{'a': 2.0, 'c': 8.0, 'b': 5.0}

use python dict comprehension

>>> mydict = {'a':[1.0, 2.0], 'b':[3.0, 4.0]}
>>> mydict = {k:float(sum(v))/len(v) for k, v in mydict.items()}
>>> mydict
{'a': 1.5, 'b': 3.5}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM