Trong bài viết này, chúng ta sẽ tìm hiểu về giải pháp cho câu hỏi được đưa ra bên dưới.
Tuyên bố sự cố - Chúng tôi được cung cấp một danh sách có thể lặp lại, chúng tôi cần tính tổng của danh sách
Ở đây chúng ta sẽ thảo luận về 3 cách tiếp cận như được thảo luận bên dưới
Sử dụng vòng lặp for
Ví dụ
# sum
total = 0
# creating a list
list1 = [11, 22,33,44,55,66]
# iterating over the list
for ele in range(0, len(list1)):
total = total + list1[ele]
# printing total value
print("Sum of all elements in given list: ", total) Đầu ra
Sum of the array is 231
Sử dụng vòng lặp while
Ví dụ
# Python program to find sum of elements in list
total = 0
ele = 0
# creating a list
list1 = [11,22,33,44,55,66]
# iterating using loop
while(ele < len(list1)):
total = total + list1[ele]
ele += 1
# printing total value
print("Sum of all elements in given list: ", total) Đầu ra
Sum of the array is 231
Sử dụng Đệ quy bằng cách tạo một hàm
Ví dụ
# list
list1 = [11,22,33,44,55,66]
# function following recursion
def sumOfList(list, size):
if (size == 0):
return 0
else:
return list[size - 1] + sumOfList(list, size - 1)
# main
total = sumOfList(list1, len(list1))
print("Sum of all elements in given list: ", total) Đầu ra
Sum of the array is 231
Kết luận
Trong bài viết này, chúng ta đã học cách in tổng các phần tử trong danh sách.