Python初学者。Python中的列表元素之和

198 阅读3分钟

Python 列表是最常用的数据结构之一。我们经常需要对列表进行不同的操作。在这篇文章中,我们将讨论在Python中寻找列表中元素之和的不同方法。

使用 For Loop 查找列表中的元素之和

找到列表中元素之和的第一种方法是使用for 循环遍历列表并添加每个元素。为此,我们将首先使用len()方法计算出列表的长度。之后,我们将声明一个变量sumOfElements 为 0。之后,我们将使用 range() 函数创建一个从 0 到(length of the list-1) 的数字序列。使用这个序列中的数字,我们可以访问给定列表中的元素,并将其添加到sumOfElements ,如下所示。

myList = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print("The given list is:")
print(myList)
list_length=len(myList)
sumOfElements=0
for i in range(list_length):
    sumOfElements=sumOfElements+myList[i]

print("Sum of all the elements in the list is:", sumOfElements)

输出。

The given list is:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Sum of all the elements in the list is: 45

另外,我们也可以使用for循环直接遍历列表。在这里,我们将直接访问列表中的每个元素,并将它们添加到sumOfElements ,如下所示。

myList = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print("The given list is:")
print(myList)
sumOfElements = 0
for element in myList:
    sumOfElements = sumOfElements + element

print("Sum of all the elements in the list is:", sumOfElements)

输出。

The given list is:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Sum of all the elements in the list is: 45

使用while循环查找列表中的元素之和

我们也可以使用 while循环来寻找列表中的元素之和。为此,我们将首先使用len()方法计算出列表的长度。之后,我们将初始化名为count和sumOfElements 的变量。我们将把这两个元素初始化为0。

在while循环中,我们将使用count变量访问列表中的每个元素,并将它们添加到sumOfElements 。之后,我们将把count的值增加1。我们将继续这个过程,直到count变成等于列表的长度。

你可以用 python 写一个程序来寻找列表中的元素之和,如下所示。

myList = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print("The given list is:")
print(myList)
list_length = len(myList)
sumOfElements = 0
count = 0
while count < list_length:
    sumOfElements = sumOfElements + myList[count]
    count = count + 1

print("Sum of all the elements in the list is:", sumOfElements)

输出。

The given list is:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Sum of all the elements in the list is: 45

使用 sum() 函数计算列表中的元素之和

Python 还为我们提供了一个内置的 sum() 函数来计算任何集合对象中的元素之和。sum() 函数接受一个可迭代的对象,如 list, tuple, 或 set,并返回该对象中元素的总和。

你可以用sum()函数找到一个列表中各元素的总和,如下所示。

myList = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print("The given list is:")
print(myList)
sumOfElements = sum(myList)
print("Sum of all the elements in the list is:", sumOfElements)

输出。

The given list is:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Sum of all the elements in the list is: 45

结论

在这篇文章中,我们讨论了在 python 中查找列表中元素之和的不同方法。要阅读更多关于 python 中的列表,你可以阅读这篇文章:如何在 python 中比较两个列表。你可能也喜欢这篇关于列表理解的文章。

The postSum Of Elements In A List In Pythonappeared first onPythonForBeginners.com.