Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

หาผลรวมสมาชิกในลิสต์ด้วย Python

ในบทความนี้ เราจะเรียนรู้วิธีแก้ปัญหาตามข้อกำหนดด้านล่าง

ข้อกำหนดปัญหา − เราได้รับลิสต์ iterable ต้องคำนวณผลรวมของลิสต์

ที่นี่เราจะอภิปราย 3 วิธีตามด้านล่าง

ใช้ลูป For

ตัวอย่าง

# sum
total = 0
# สร้างลิสต์
list1 = [11, 22, 33, 44, 55, 66]
# วนลูปผ่านลิสต์
for ele in range(0, len(list1)):
    total = total + list1[ele]
# พิมพ์ค่ารวม
print("Sum of all elements in given list:", total)

ผลลัพธ์

Sum of the array is 231

ใช้ลูป While

ตัวอย่าง

# Python program to find sum of elements in list
total = 0
ele = 0
# สร้างลิสต์
list1 = [11, 22, 33, 44, 55, 66]
# วนลูปด้วย while
while ele < len(list1):
    total = total + list1[ele]
    ele += 1
# พิมพ์ค่ารวม
print("Sum of all elements in given list:", total)

ผลลัพธ์

Sum of the array is 231

ใช้ Recursion โดยสร้างฟังก์ชัน

ตัวอย่าง

# list
list1 = [11, 22, 33, 44, 55, 66]

# ฟังก์ชันใช้ 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)

ผลลัพธ์

Sum of the array is 231

สรุป

ในบทความนี้ เราได้เรียนรู้ 3 วิธีหาผลรวมสมาชิกในลิสต์: for loop, while loop, และ recursion วิธีที่ง่ายที่สุดคือใช้ built-in sum() function