对给定列表 Python 的给定范围内的所有数字求和 [英] Sum all numbers in a given range of a given list Python

查看:81
本文介绍了对给定列表 Python 的给定范围内的所有数字求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何编写一个函数来获取给定列表中索引 a 和 b 之间的项的总和.例如给 aList=[6,3,4,2,5]a=1, b=3,函数应该返回9. 这是我的代码:

How can I write a function to get the sum of the items in the given list between the indices a and b. For example give aList=[6,3,4,2,5] and a=1, b=3, the function should return 9. Here is my code:

def sumRange(L,a,b):
    sum= []
    L = [6,3,4,2,5]
    for i in range(a,b+1,1):
    sum +=L[i]
    return sum

推荐答案

您似乎想要推出自己的解决方案.你可以这样做(根据你在问题中的代码):

It seems like you want do roll your own solution. You can do it like this (based on the code you had in your question):

def sumRange(L,a,b):                                                                                                                                                                                                
    sum = 0                                                                                                                                                                                                         
    for i in range(a,b+1,1):                                                                                                                                                                                        
        sum += L[i]                                                                                                                                                                                                  
    return sum                                                                                                                                                                                                      

L = [6,3,4,2,5]                                                                                                                                                                                                     
a = 1                                                                                                                                                                                                               
b = 3                                                                                                                                                                                                               

result = sumRange(L,a,b)                                                                                                                                                                                            

print "The result is", result

这个程序打印

结果是 9

这篇关于对给定列表 Python 的给定范围内的所有数字求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆