在 Python 中獲取列表的總和

在 Python 中用 `sum()` 函式對一個列表求和

``````myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
listSum = sum(myList)
print(f"Sum of list -> {listSum}")
``````

``````Sum of list -> 55
``````

`sum()` 函式接受兩個引數。第一個引數是可迭代的資料結構，第二個引數是起始索引。可迭代的資料結構可以是數字，Python 字典和元組的列表。起始索引基本上是可迭代資料結構中求和過程應從其開始的位置。

``````myList = ["1", "3", "5", "7", "9"]
myNewList = [int(string) for string in myList]
sum1 = sum(myNewList)
sum2 = sum(number for number in myNewList)
print(f"Sum of list -> {sum1}")
print(f"Sum of list -> {sum2}")
``````

``````Sum of list -> 25
Sum of list -> 25
``````

通過遍歷列表獲取列表的總和

``````myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
listSum = 0

for number in myList:
listSum += number

print(f"Sum of list -> {listSum}")
``````

``````Sum of list -> 55
``````

``````myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
length = len(myList)
listSum = 0

for i in range(length):
listSum += myList[i]

print(f"Sum of list -> {listSum}")
``````

``````Sum of list -> 55
``````

Vaibhav is an artificial intelligence and cloud computing stan. He likes to build end-to-end full-stack web and mobile applications. Besides computer science and technology, he loves playing cricket and badminton, going on bike rides, and doodling.