python - 从列表中的某个点计算列表的平均值?

标签 python arrays list math

我有一个问题,我知道可以计算列表的平均值,但是是否可以从某个点计算平均值?

例如:

def Average(lst): 
    return sum(lst) / len(lst)

list = [2, 8, 6, 7, 3, 2, 1]
average = Average(lst) 

列表的打印平均值:

print("Average of the list =", round(average, 2))

输出: 列表平均值 = 4.14

假设我们要保留前 3 个值,并对其余值进行平均,使列表中只有 4 个值

所以我的新列表是:

list = [2, 8, 6, 7, 3, 2, 1] 
new_list = [2, 8, 6, 12.25]

编辑 1

谢谢大家的回答。我还有另一个问题,比如说,我不知道列表的长度,我只想在新列表中包含 4 个元素。我该如何解决这个问题?

最佳答案

假设您想根据索引对列表进行四舍五入(此处为 3)

mylist = [2, 8, 6, 7, 3, 2, 1]

def round_list(lst, index):
    avg = [sum(lst[int(index):])/(len(lst)-index)]
    new_lst = (lst[:int(index)]) + avg
    return new_lst

new_list = round_list(mylist, 3)
print(new_list)

输出:[2,8,6,3.25]

关于python - 从列表中的某个点计算列表的平均值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60280083/

相关文章:

javascript - 将引用设置为其他内容后保留 Javascript 引用

javascript - 试图从数组中检索对象的颜色

c - 如何在C中返回指向数组的指针?

python - 在 python 中填充列表

c# - 按多个标准对 List<> 中的对象进行排名

c# 如何从 List<T> 创建 SortableBindingList

python - CAN模块python 3

python - PyMysql编码问题

python - 在 Fedora 24 上为 Python 3 安装 OpenCV

python - Tensorflow 估计器 ValueError : logits and labels must have the same shape ((? , 1) vs (?,))