Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum two lists items in python [closed]

Tags:

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 for 'A' and 'C' such that 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]

i.e, result=[-0.5, -0.5, 0.0]

How can I compute the result ? Note that my_list=['A','C'] is not fixed, so please do not use fixed values.

EDIT: my_list=['A','C'] is a variable passed to a function. It could be for example ['A','B','C']. So please, consider this. I can not use 'A' and 'C' explicitly in the code.

like image 336
user2192774 Avatar asked Dec 21 '22 03:12

user2192774


2 Answers

Sounds like you really want to be using 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 normal python this is:

[sum(values)/float(len(my_list)) for values in zip(*[my_dict[key] for key in my_list])]
like image 122
U2EF1 Avatar answered Dec 22 '22 15:12

U2EF1


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 then you 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 yields:

[-0.666, -0.666, -0.333]
like image 22
perreal Avatar answered Dec 22 '22 15:12

perreal