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

หาผลรวมสะสม (Cumulative Sum) ของ List ใน Python

หาผลรวมสะสม โดยแต่ละตำแหน่ง i คือผลรวมของสมาชิกแรก i+1 ตัว ใช้ List Comprehension

ตัวอย่างโค้ด

def cumulative_sum(my_list):
    cumulative_list = []
    my_length = len(my_list)
    cumulative_list = [sum(my_list[0:x:1]) for x in range(0, my_length+1)]
    return cumulative_list[1:]

my_list = [10, 20, 25, 30, 40, 50]
print("The list is :")
print(my_list)
print("The cumulative sum is :")
print(cumulative_sum(my_list))

ผลลัพธ์

The list is : [10, 20, 25, 30, 40, 50]
The cumulative sum is : [10, 30, 55, 85, 125, 175]

คำอธิบาย

  • ใช้ List Comprehension วน x จาก 0 ถึงความยาว List
  • sum(my_list[0:x:1]) หาผลรวมสมาชิกแรก x ตัว
  • ตัดตัวแรกออก (index 0) เพราะเป็นค่าว่าง