<>python Summation function sum() Detailed explanation
<> Today in the process of learning , misuse sum() function , I checked again python sum() The function came to light .
I wanted to count a few Int Sum of added values , I thought it was very simple , It turned out to be sad , example :
>>>sum = sum(1,2,3) # As a result, it was obvious that there was a problem and an error was reported TypeError: sum expected at most 2 arguments,
got 3
Stupid. I thought it was the sum of the first two numbers 3, I tried again
>>>sum = sum(1,2) # It turned out to be a mistake TypeError: 'int' object is not iterable
actually , What we know sum() The functional syntax is like this
sum(iterable[, start])
among
*
iterable – Iteratable object , as : list (list), tuple (tuple), aggregate (set), Dictionaries (dictionary).
*
start – Specifies the parameters for the addition , If this value is not set , Default to 0.
in other words sum() The final value = The sum of the numbers in an iteratable object ( Dictionaries :key Value addition ) + start Value of ( If not start Value of , The default value is 0)
therefore , What I asked for int The sum of values can be written like this
>>>sum = sum([1,2,3]) # in list 6
If we add start In my words , It should be like this
>>> sum = sum([1,2,3],5) #in list +start 11 >>> sum = sum((1,2,3)) #in tuple 6
>>> sum = sum({1,2,3}) #in set 6 >>> sum = sum({1:5,2:6,3:7}) #in dictionary key
6 >>> sum = sum(range(1,4)) #in range() 6
After learning these , We can use it correctly sum() Function .
Don't expect to remember and master anything by looking at it once – Please watch it for the second time , The third time .
Technology