我有一个 for
循环,它提供了以下输出。
0.53125
0.4375
0.546875
0.578125
0.75
0.734375
0.640625
0.53125
0.515625
0.828125
0.5
0.484375
0.59375
0.59375
0.734375
0.71875
0.609375
0.484375
.
.
.
如何找到前 9 个值、后 9 个值等的平均值,并将它们存储到像 [0.58,0.20,...]
这样的列表中?我尝试了很多方法,但这些值似乎不正确。这样做的正确方法是什么?
我做了什么:
matchedRatioList = []
matchedRatio = 0
i = 0
for feature in range(90):
featureToCompare = featuresList[feature]
number = labelsList[feature]
match = difflib.SequenceMatcher(None,featureToCompare,imagePixList)
matchingRatio = match.ratio()
print(matchingRatio)
matchedRatio += matchingRatio
if i == 8:
matchedRatioList.append(matchedRatio / 9)
i = 0
matchedRatio = 0
i += 1
最佳答案
获得数字列表后,您可以使用列表推导式计算每组 9 个数字的平均值:
from statistics import mean
numbers = [0.53125, 0.4375, 0.546875, 0.578125, 0.75, 0.734375, 0.640625,
0.53125, 0.515625, 0.828125, 0.5, 0.484375, 0.59375, 0.59375,
0.734375, 0.71875, 0.609375, 0.484375]
group_len = 9
matched_ratios = [mean(group) for group in [numbers[i:i+group_len]
for i in range(0, len(numbers), group_len)]]
print(matched_ratios)
# [0.5850694444444444, 0.6163194444444444]
关于python - 从 for 循环中查找前 9 个数字的平均值,然后查找接下来的 9 个数字,依此类推,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41344076/