Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 需要创建一个函数cumsum,该函数返回列表l的累积和_Python - Fatal编程技术网

Python 需要创建一个函数cumsum,该函数返回列表l的累积和

Python 需要创建一个函数cumsum,该函数返回列表l的累积和,python,Python,完整说明:编写一个函数cumsum,该函数采用 将l列为参数,并返回l的累积和(也称为前缀和),这是一个列表,例如与l长度相同的cs,使得每个元素cs[i]等于l的前i+1个元素的和 到目前为止,我有这个问题,但我不知道我哪里出了问题,因为它一直未能通过所有的测试 **也不能假定列表中的某个数据类型(可以是字符串、整数等)。我如何初始化它,以便它可以用于任何数据类型 到目前为止,我的代码是: def cumsum(l): cs = [] total = 0 for x in r

完整说明:编写一个函数cumsum,该函数采用 将l列为参数,并返回l的累积和(也称为前缀和),这是一个列表,例如与l长度相同的cs,使得每个元素cs[i]等于l的前i+1个元素的和

到目前为止,我有这个问题,但我不知道我哪里出了问题,因为它一直未能通过所有的测试

**也不能假定列表中的某个数据类型(可以是字符串、整数等)。我如何初始化它,以便它可以用于任何数据类型

到目前为止,我的代码是:

def cumsum(l):

  cs = []

  total = 0

  for x in range(l):

    total = total + x

    cs.append(total)

  return cs
(注意:我不能使用任何导入或额外工具,应该使用append函数)
有人知道我能做些什么来让它工作吗?

在穆罕默德的答案的基础上,输入cast x to int

def cumsum(l):    
  cs = []    
  total = 0    
  for x in l:    
    total = total + int(x)
    cs.append(total)
  return cs

如果可以假设所有元素都是同一类型,则这适用于数字和字符串:

def cumsum(l):
  cs = []
  total = None
  for x in l:
    if total is None:
        total=x
    else:
        total = total + x
    cs.append(total)
  return cs

print(cumsum([1,2,3]))

... 但这取决于如何定义字符串的总和,我假设字符串是串联的