作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
下面给出了我的代码,但我无法使其循环。在此代码中,totd_list
是一些随机数的列表。我想要对索引号 1 求平均值,然后对接下来的两个索引求平均值,然后对接下来的三个索引求平均值,然后对接下来的 4 个索引求平均值。如何放置 for 循环以获得更不错的结果?
avg[0]=totd_list[0]
avg[1]=(totd_list[1]+totd_list[2])/2
avg[2]=(totd_list[3]+totd_list[4]+totd_list[5])/3
avg[3]=(totd_list[6]+totd_list[7]+totd_list[8]+totd_list[9])/4
avg[4]=(totd_list[10]+totd_list[11]+totd_list[12]+totd_list[13]+totd_list[14])/5
最佳答案
这可以通过理解来完成,但有点复杂:
totd_list = [2] * 15
an_iter = iter(totd_list)
sums = [sum((next(an_iter) for j in range(i+1))) for i in range(5)]
print(sums)
avg = [s / (i+1) for i, s in enumerate(sums)]
print(avg)
[2, 4, 6, 8, 10]
[2, 2, 2, 2, 2]
关于python - 我如何为这个给定的列表放置 for 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48958379/
我是一名优秀的程序员,十分优秀!