Skip to main content
 首页 » 编程设计

python 列表索引越界

2025年05月04日15haluo1

大家好,我是第一次来!

作为一项任务,我得到了这个:现在创建一个新函数 cumulative_sum,它返回一个新列表,其中第 i 个元素是原始列表中前 i+1 个元素的总和。例如[4,3,6]的累加和为[4,7,13]。

所以我写了这段代码:

list_1 = [4, 6, 3] 
 
def cumulative_sum(a_list): 
    list_2 = [] 
    list_2.append(a_list[0]) 
    x = 1 
    y = 0 
        for i in a_list: 
            if len(a_list) == x: 
               break 
            else: 
                var1 = list_2[x] 
                var2 = a_list[y] 
                var3 = var1 + var2 
                list_2.append(var3) 
                x +=1 
                y +=1 
                return list_2 
print cumulative_sum(list_1) 

然而,即使我有像这样的绑定(bind)检查,我仍然会收到索引超出范围的错误:

        if len(a_list) == x: 
        break 

对不起我的英语!欢迎提供有关我的代码的任何其他提示

这是回溯:

 IndexError                                Traceback (most recent call last) 
 /Applications/Canopy.app/appdata/canopy-1.4.1.1975.macosx-x86_64/Canopy.app/Contents/lib/python2.7/site-packages/IPython/utils/py3compat.pyc in execfile(fname, *where) 
202             else: 
203                 filename = fname 
--> 204             __builtin__.execfile(filename, *where) 
 
/Users/arkin/programming/multadd.py in <module>() 
 97             return list_2 
 98  
---> 99 print cumulative_sum(list_1) 
100  
101  
 
/Users/arkin/programming/multadd.py in cumulative_sum(a_list) 
 89             break 
 90         else: 
---> 91             var1 = list_2[x] 
 92             var2 = a_list[y] 
 93             var3 = var1 + var2 

请您参考如下方法:

您不能将元素分配到列表中尚不存在的索引处。你应该使用 append 来做到这一点。

def cumulative_sum(l): 
    total = 0          # initialize the total to zero 
    cumulative = []    # initialize an empty list 
    for num in l:      # iterate over each number in original list 
        total += num   # calculate the cumulative total to this element 
        cumulative.append(total)   # append to the cumulative list 
    return cumulative 

使用您的示例输入和输出

>>> cumulative_sum([4,3,6]) 
[4, 7, 13] 

编辑
较短的方法是使用一些 Python 库

import itertools 
import operator 
 
def cumulative_sum(l): 
    return list(itertools.accumulate(l, operator.add))