gpt4 book ai didi

python - 在python中查找列表的一部分的平均值,然后修改列表

转载 作者:行者123 更新时间:2023-12-01 20:17:34 25 4
gpt4 key购买 nike

我有一个这样的列表

x = [4342, 318, 262, 6827, 314, 765, 11525, 67, 654, 13]


我想取11525,67和654的平均值,然后将其放在索引11525处。所以,基本上我希望我的列表 x 是这样的:-

x = [4342, 318, 262, 6827, 314, 765, 4082, 13]

我知道如何取平均值,但不知道如何通过删除索引来修改列表。这就是我到目前为止所做的

sum = 0
count = 0
for x in range(6, 9):
sum += text_index[x]
count += 1
print(sum, count)
avg = int(sum/count)
print(avg)

现在,我应该如何编辑列表以获得所需的输出?

最佳答案

targets = []
for i in range(6,9):
targets.append(text_index.pop(i)) # use pop to remove the item and return it
sum = sum(text_index) # Use sum() on an iterable to sum each item
avg = sum/len(targets) # Calculate the mean using the len

关于python - 在python中查找列表的一部分的平均值,然后修改列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61837600/

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