Search code examples
pythonpython-3.xlistsummultiplication

Multiplying two lists in a sum


I have a formula (image attached) that I need to use. I have two lists, x and y. My issue is that I need to multiply these two lists in the formula for M. But it seems that I can not multiply lists in python. How can I code for M using two lists? Here is my current code

m = (1/D)sum((([(xi-xbar) for xi in x]))*([(yi*1) for yi in y]))
print('m',m)

I get the error "can't multiply sequence by non-int of type 'list'"

How do I multiply two lists, thanks!

Formula


Solution

  • You want to do this.

    m=sum((xi-mean(x))*yi)

    You can try this.

    from statistics import mean
    x=[1,2,3,4,5]
    y=[6,7,8,9,10]
    
    mean_x=mean(x)
    
    m=(1/D)*sum((i-mean_x)*j for i,j in zip(x,y))
    c=mean(y)-(m*mean_x)