取切片列表的平均值

Taking the average of a sliced list

我遇到的问题是试图取我的列表的平均值(从 y 导出,它是 sin 值的列表)。但是,当 运行 代码时,我得到错误

TypeError: float() 参数必须是字符串或数字,而不是 'list'

如果您能提供任何帮助,我们将不胜感激

for k in range(len(y)-1-r):

    list_to_avg = [y[r+k:len(y)-1-r+k]]
    b =float(sum(list_to_avg, []))
    a =float(len(list_to_avg))
    z.append(b/a)

您已创建 list_to_avg 一个包含列表的列表。

使用

list_to_avg = y[r+k:len(y)-1-r+k]

相反。

改变这个:

b = float(sum(list_to_avg, []))

对此:

b = float(sum(list_to_avg))

您要求 sumlist_to_avg 的任何内容添加一个空列表 ([])。


因为第 b = float(sum(list_to_avg, [])) 行没有抛出:

TypeError: can only concatenate list (not "whatever1") to list

表示list_to_avg是列表的列表。我不知道这是不是故意的,所以我假设是。但如果是,求和的结果也将是 list,当然不能转换为 float,因此:

TypeError: float() argument must be a string or a number, not 'list'


1随便都是我的。例如,如果你有 sum([1, 2, 3], []) 它会说 TypeError: can only concatenate list (not "int") to list