简体   繁体   English

元素列表乘和

[英]element list multiply sum

How would I multiply and obtain the sum of the lists in the following lists WITHOUT the use of numpy? 在不使用numpy的情况下,如何乘以并获得以下列表中列表的总和?

pattern = [40, 30, 20, 10]
data_list =[[-1, 2, -2, 3], [2, -2, 3, 41], [-2, 3, 41, 38], \
[3, 41, 38, 22], [41, 38, 22, 10], [38, 22, 10, -1], [22, 10, -1, 3]]

I want to multiply each element in the data_list by the pattern and obtain the following result. 我想将data_list中的每个元素乘以该模式并获得以下结果。

expected_answer = [10, 490, 1210, 2330, 3320, 2370, 1190]

I've tried: 我试过了:

sum([i*j for i,j in zip(data_list, pattern)])

yet I keep getting this error: 但我一直收到此错误:

TypeError: unsupported operand type(s) for +: 'int' and 'list'

You want to convolve pattern over data_list ? 您想在data_list上卷积pattern吗?

Iterate on data_list and take the sum of the products of each element in the iteratee sublist and the corresponding element in pattern : 迭代上data_list并采取在iteratee子列表的每个元素,并在相应元件的乘积的和pattern

answer = [sum(x*y for x, y in zip(lst, pattern)) for lst in data_list]
print(answer)
# [10, 490, 1210, 2330, 3320, 2370, 1190]

About your error: i * j performs a list multiplication/replication (not what you want), since i is a list and j is an integer, and then sum tries to add the first resulting list to the default start parameter 0 . 关于您的错误: i * j执行列表乘法/复制(不是您想要的),因为i是一个列表并且j是一个整数,然后sum尝试将第一个结果列表添加到默认的start参数0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM