如何对列表的每个值求和
How to make sum of each value of list
# List_values = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
# Example :
# 21 = 1+2+3+4+5+6
# 27 = 2+3+4+5+6+7
# 33 = 3+4+5+6+7+8
# 39 = 4+5+6+7+8+9
# Output = [21,27,33,39,45,51,57,63,69,75] # till 10 times
I am trying to make the sum of 0 index value to Nth index and then skip first index value(1) and start making sum from second index value(2) to Nth index value
我认为您至少需要一个循环来遍历列表。
以下是我解决您的问题的方法:
# creating a list
list1 = [1, 2, 3, 4, 5]
for i in range(len(list1)):
sm = sum(list1[i:len(list1)]) # Sum of 'a' from 0th index to 4th index. sum(a) == sum(a[0:len(a)]
print(sm)
你要这个吗? -
n = 5 # specify the value of n
result = [sum(l[i:(i+n+1)]) for i in range(len(l)-n)][:10]
print(result)
这里的思路是一次计算5个元素的和,然后从列表中取前10个元素。
[21, 27, 33, 39, 45, 51, 57, 63, 69, 75]
# List_values = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
# Example :
# 21 = 1+2+3+4+5+6
# 27 = 2+3+4+5+6+7
# 33 = 3+4+5+6+7+8
# 39 = 4+5+6+7+8+9
# Output = [21,27,33,39,45,51,57,63,69,75] # till 10 times
I am trying to make the sum of 0 index value to Nth index and then skip first index value(1) and start making sum from second index value(2) to Nth index value
我认为您至少需要一个循环来遍历列表。 以下是我解决您的问题的方法:
# creating a list
list1 = [1, 2, 3, 4, 5]
for i in range(len(list1)):
sm = sum(list1[i:len(list1)]) # Sum of 'a' from 0th index to 4th index. sum(a) == sum(a[0:len(a)]
print(sm)
你要这个吗? -
n = 5 # specify the value of n
result = [sum(l[i:(i+n+1)]) for i in range(len(l)-n)][:10]
print(result)
这里的思路是一次计算5个元素的和,然后从列表中取前10个元素。
[21, 27, 33, 39, 45, 51, 57, 63, 69, 75]