內置的 Python sum() Functions are another powerful tool,whenever you are there Python processing digital data.sum() The first argument to the function should be a collection of numbers you want to add up.These values can be contained in a list、元組、集合或字典中.與sum()The optional second argument used with the function is 'start'參數.This will add a numerical value to the final result.如果你試圖用 sum() Use a non-numeric data type,Python 將拋出一個錯誤.現在讓我們看看sum()A few examples of how it works.
The first example shows a list of integers stored in a variable.We can pass that variable to sum()函數,It adds them all up and returns the result to us.
list_of_ints = [1, 9, 4, 6, 7, 7, 2]
the_sum = sum(list_of_ints)
print(the_sum)
復制代碼
36
復制代碼
example twosum()There is a list of floats.Again we pass the list of floats to sum()函數,It gives us results faster than we can do in our heads.
list_of_floats = [1.5, 9.2, 4.9, 6.1, 7.8, 7.7, 2.1234]
the_sum = sum(list_of_floats)
print(the_sum)
復制代碼
39.32340000000001
復制代碼
Example threesum()does use optionalstart參數.We can see that we are adding1+1,當然是2,但是由於我們使用了10的起點,So the end result is actually12.
list_of_ints = [1, 1]
the_sum = sum(list_of_ints, start=10)
print(the_sum)
復制代碼
12
復制代碼
例四:sum()The function adds all integer values stored in a tuple.
tuple_of_ints = (2, 4, 10)
the_sum = sum(tuple_of_ints)
print(the_sum)
復制代碼
16
復制代碼
在sum()Example 5 of the function,We add up some floats stored in a tuple.
tuple_of_floats = (2.55, 4.123, 10.987)
the_sum = sum(tuple_of_floats)
print(the_sum)
復制代碼
17.66
復制代碼
Example 6 shows how to use itsum()with a tuple of integers and optionalstart參數.
tuple_of_ints = (2, 4, 10)
the_sum = sum(tuple_of_ints, start=20)
print(the_sum)
復制代碼
36
復制代碼
Example 7 is very interesting,Because we are using a collectionsum()函數.The result below will be2+2+4The result after adding is 6.This is because the set removes duplicates before completing the sum operation 2.
set_of_ints = {2, 2, 4}
the_sum = sum(set_of_ints)
print(the_sum)
復制代碼
6
復制代碼
我們可以看一下 sum() The last example of a function,It is the sum of the keys in a dictionary.
the_dict = {5: 'The contents in 5',
7: 'What is stored in seven',
2: 'One more value'}
result = sum(the_dict)
print(result)
復制代碼
14
復制代碼
如果你想在 Python Sums all values of a dictionary in ,你可以這樣做.
the_dict = {'a': 2, 'b': 4, 'c': 6}
result = sum(the_dict.values())
print(result)
復制代碼
12
復制代碼