程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python sum() function

編輯:Python

內置的 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.


with a list of integers sum()

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
復制代碼

with a list of floatssum()

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
復制代碼

with a list of integers and an optional startsum()函數

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
復制代碼

with integer groupssum()函數

例四: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
復制代碼

A tuple of floatssum()

在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
復制代碼

A tuple with integers and an optional starting numbersum()

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
復制代碼

with a set sum()

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()

我們可以看一下 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
復制代碼

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved