我有一个问题,我知道可以计算列表的平均值,但是是否可以从某个点计算平均值?
例如:
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/