简体   繁体   中英

element list multiply sum

How would I multiply and obtain the sum of the lists in the following lists WITHOUT the use of 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.

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 ?

Iterate on data_list and take the sum of the products of each element in the iteratee sublist and the corresponding element in 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 .

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