简体   繁体   中英

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!

公式

You want to do this.

m=sum((x i -mean(x))*y i )

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)

You can use the zip function in python to do pair 2 lists.

list_a=[1,2,3]
list_b=[4,5,6]
multiplied_ab=[]
for i,j in zip(list_a,list_b):
    multiplied_ab.append(i,j)
print(multiplied_ab)

Your result will be multiplication of the 2 lists like this: [4,10,18]

You'll have to make sure that the length of the 2 lists match.

Then you can simply calculate the sum of the list by using the sum() function

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