can somebody help me with a code error.
What I need is to multiply 2nd and 3rd element of each list and then sum up four values (total result=431900) I've done it with a simple for loop:
lst = [['switch', '4', '12500'], ['hub', '1', '500'], ['router', '1', '1400'], ['jacks', '40', '9500']]
summ = 0
for i in lst:
summ = int(i[1])*int(i[2])
print(summ)
But I wanted to improve it with a function or lambda:
from functools import reduce
result = reduce(lambda x, y: int(x[1])*int(x[2])) (int(y[1])*int(y[2]), lst)
print(result)
It returns only first iteration (50500), on second x becomes None (y becomes the next list) and the program returns an error: TypeError: 'NoneType' object is not subscriptable.
I don't get why x becomes None, what is wrong here?
CodePudding user response:
Note that once you have summed, x
is now a double and not a list thus not subscriptable. You thus need to make use of the initial
(ie 3rd) parameter. Ans since its a sum, we start summing from 0.
reduce(lambda x, y: x int(y[1]) * int(y[2]), lst, 0)
Out[230]: 431900