简体   繁体   中英

Python - Compute average of integers in dictionary values (nested lists)

It is so hard to describe my question in words so here is a simple example of what I'm trying to do.

I have a dictionary ...

aDict= {'user1':[[1,2,3],[4,5,6]], 'user2': [[2,3,4],[5,6,7]]}

I want to compute averages of numbers in the same index in the nested loop.

Ideal result I would like to get is...

anotherDict = {'user' : [[1.5 , 2.5 , 3.5 ],[ 4.5 , 5.5 , 6.5 ]]}

1.5 = average of 1 from key-user1.values[0][0] and 2 from key-user2.values[0][0] 2.5 = average of 2 from key-user1.values[0][1] and 3 from key-user2.values[0][1] ... so on... 6.5 = average of 6 from key-user1.values[1][2] and 7 from key-user2.values[1][2]

I am really new to python and I really apologize for the difficult explanation of my problem.

Thanks for help in advance.

You can use the following nested comprehension using lots of zip(*...) transpositioning:

aDict= {'user1':[[1,2,3],[4,5,6]], 'user2': [[2,3,4],[5,6,7]]}
[[sum(x)/len(x) for x in zip(*vals)] for vals in zip(*aDict.values())]
# [[1.5, 2.5, 3.5], [4.5, 5.5, 6.5]]

In Python2, you'd have to take some measures to get float values, eg:

[[1.0*sum(x)/len(x) for x in zip(*vals)] for vals in zip(*aDict.values())]

map +list comprehension way of @schwobaseggl's solution:

print([list(map(lambda x: sum(x)/len(x),zip(*v))) for v in zip(*aDict.values())])

And to assign it to a new dict:

d={'user':[list(map(lambda x: sum(x)/len(x),zip(*v))) for v in zip(*aDict.values())]}

Or map + map way of @schwobaseggl's solution:

print(list(map(lambda v: list(map(lambda x: sum(x)/len(x),zip(*v))),zip(*aDict.values()))))

And to assign it to a new dict:

d={'user':list(map(lambda v: list(map(lambda x: sum(x)/len(x),zip(*v))),zip(*aDict.values())))}

Do from __future__ import division if version under 3 and over 2.2, to get python 3 style division

They all output:

[[1.5, 2.5, 3.5], [4.5, 5.5, 6.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