写一个 Python示例,用一个实际例子找到列表中元素的和。
这个 python 程序允许用户输入列表的长度。接下来,我们使用 Python For Loop 向列表中添加数字。
Python sum 函数返回列表中所有元素的 sum 。
# Python Program to find Sum of all Elements in a List
NumList = []
Number = int(input("Please enter the Total Number of List Elements : "))
for i in range(1, Number + 1):
value = int(input("Please enter the Value of %d Element : " %i))
NumList.append(value)
total = sum(NumList)
print("\n The Sum of All Element in this List is : ", total)
在这个程序中,我们使用 For Loop 来迭代这个列表中的每个元素。在循环中,我们将这些元素添加到总变量中。
NumList = []
total = 0
Number = int(input("Please enter the Total Number of List Elements : "))
for i in range(1, Number + 1):
value = int(input("Please enter the Value of %d Element : " %i))
NumList.append(value)
for j in range(Number):
total = total + NumList[j]
print("\n The Sum of All Element in this List is : ", total)
Python 列表项的总和输出
Please enter the Total Number of List Elements : 5
Please enter the Value of 1 Element : 10
Please enter the Value of 2 Element : 20
Please enter the Value of 3 Element : 30
Please enter the Value of 4 Element : 40
Please enter the Value of 5 Element : 55
The Sum of All Element in this List is : 155
这个返回列表项总和的 Python示例与上面的相同。我们刚刚将 For 循环替换为 While 循环。
NumList = []
total = 0
j = 0
Number = int(input("Please enter the Total Number of List Elements : "))
for i in range(1, Number + 1):
value = int(input("Please enter the Value of %d Element : " %i))
NumList.append(value)
while(j < Number):
total = total + NumList[j]
j = j + 1
print("\n The Sum of All Element in this List is : ", total)
使用 while 循环输出的列表项的总和
Please enter the Total Number of List Elements : 6
Please enter the Value of 1 Element : 10
Please enter the Value of 2 Element : 20
Please enter the Value of 3 Element : -30
Please enter the Value of 4 Element : -40
Please enter the Value of 5 Element : 50
Please enter the Value of 6 Element : 100
The Sum of All Element in this List is : 110
这个求列表项总和的程序和第一个例子一样。但是,我们使用函数分离了 python 程序逻辑。
def sum_of_list(NumList):
total = 0
for j in range(Number):
total = total + NumList[j]
return total
NumList = []
Number = int(input("Please enter the Total Number of List Elements : "))
for i in range(1, Number + 1):
value = int(input("Please enter the Value of %d Element : " %i))
NumList.append(value)
total = sum_of_list(NumList)
print("\n The Sum of All Element in this List is : ", total)
使用函数输出的列表项的总和
Please enter the Total Number of List Elements : 7
Please enter the Value of 1 Element : 19
Please enter the Value of 2 Element : 11
Please enter the Value of 3 Element : 32
Please enter the Value of 4 Element : 86
Please enter the Value of 5 Element : 567
Please enter the Value of 6 Element : 32
Please enter the Value of 7 Element : 9
The Sum of All Element in this List is : 756
标签: 轻量云