gpt4 book ai didi

python - 我如何为这个给定的列表放置 for 循环?

转载 作者:行者123 更新时间:2023-12-01 02:07:00 24 4
gpt4 key购买 nike

下面给出了我的代码,但我无法使其循环。在此代码中,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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com