Search code examples
pythonlistprintingmultiplication

List of Lists | Multiply sub-elements, Add answers (Python)


Thank you very much everyone who helped answer. These all work as should and have been appendable. As no demonstrated below.

I am wanting to print working out of multiplication and addition.

import numpy as np

# [x, w] including bias
X = [[0.5, 0.15], [0.1, -0.3], [1, 0]]

in_str = 'in = '
for input in X:
  substr = '('+str(input[0])+' x '+str(input[1])+') + '
  in_str += substr
in_str = in_str[:-3]
print(in_str)

calcs = [x * y for x, y in X]
in_str = '   = '
for c in calcs:
  substr = '('+str(c)+') + '
  in_str += substr
in_str = in_str[:-3]
print(in_str)

ans = sum([x * y for x, y in X])
print('   = ' + str(ans))

Output:

in = (0.5 x 0.15) + (0.1 x -0.3) + (1 x 0)
   = (0.075) + (-0.03) + (0)
   = 0.045

Solution

  • Use list comprehension:

    ans=sum([x*y for x,y in X])