Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to dot product 1D and 2D lists in python without using NumPy or .dot?

With given 2D and 1D lists, I have to dot product them. But I have to calculate them without using .dot.

For example, I want to make these lists

matrix_A = [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15], [16, 17, 18, 19], [20, 21, 22, 23], [24, 25, 26, 27], [28, 29, 30, 31]]
vector_x = [0, 1, 2, 3]

to this output

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

result_list = [ 14  38  62  86 110 134 158 182]

How can I do it by only using lists(not using NumPy array and .dot) in python?

>Solution :

You could use a list comprehension with nested for loops.

matrix_A = [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15], [16, 17, 18, 19], [20, 21, 22, 23], [24, 25, 26, 27], [28, 29, 30, 31]]
vector_x = [0, 1, 2, 3]

result_list = [sum([a*b for a,b in zip(row, vector_x)]) for row in matrix_A]

print(result_list)

Output:

[14, 38, 62, 86, 110, 134, 158, 182]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading