How to sum two list items in python

I have a dictionary:

my_dict = {'A': [-1,-1,-1], 'B': [-1,-1,-1], 'C': [0,0,1]} my_list=['A','C'] 

I want to find the average value for "A" and "C", so the average is a new list that contains the values ​​for the dictionary keys A and C, divided by 2:

 result=[(-1+0)/2, (-1+0)/2, (-1+1)/2] 

ie, result=[-0.5, -0.5, 0.0]

How can I calculate the result? Please note that my_list=['A','C'] not fixed, so please do not use fixed values.

EDIT: my_list=['A','C'] is the variable passed to the function. It can be, for example, ['A', 'B', 'C']. Please think about it. I cannot use "A" and "C" explicitly in code.

+4
source share
2 answers

It sounds like you really want to use pandas, or at least numpy. In pandas, this is:

 import pandas as pd data = pd.DataFrame({'A': [-1,-1,-1], 'B': [-1,-1,-1], 'C': [0,0,1]}) my_list = ['A', 'C'] data[my_list].mean(axis=1) 

In any case, in ordinary python it is:

 [sum(values)/float(len(my_list)) for values in zip(*[my_dict[key] for key in my_list])] 
+8
source
 from __future__ import division # for python < 3 only my_dict = {'A': [-1,-1,-1], 'B': [-1,-1,-1], 'C': [0,0,1]} my_list=['A','C'] l = [] for v in zip(*(my_dict[x] for x in my_list)): l += [ sum(v) / len(v) ] 

If you have Python 2.x, you will need the future. division for float division. The above should work for any number of items in my_list . For example, for my_list = ['A,' B', 'C'] it gives:

 [-0.666, -0.666, -0.333] 
+3
source

Source: https://habr.com/ru/post/1491304/


All Articles