I am trying to find total of all the integers in a tuple
from functools import reduce
marks = [("Jon" ,29 ), ("santi",35), ("anna",35)]
Total_marks = lambda x,y: x[1]
print(marks)
print (reduce(Total_marks,marks))
The above code can take the first value of integer, but i want to find the sum of all the integers, how to do it using reduce in python
Change the definition of the adding function (there is no need to use lambda notation here):
def total_marks(x, y):
return x + y[1]
And tell reduce that the initial value is a number, not a tuple, by providing the third optional parameter:
reduce(total_marks, marks, 0)
#99
The same solution with lambda:
reduce(lambda x,y: x+y[1], marks, 0)
And one more solution that does not use reduce:
_, y = zip(*marks)
sum(y)
#99
If using reduce is not necessary, a much more elegant solution is
marks = [("Jon" ,29 ), ("santi",35), ("anna",35)]
total_marks = sum(score for _, score in marks)
print(total_marks)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With