python - 从 for 循环中查找前 9 个数字的平均值,然后查找接下来的 9 个数字,依此类推

标签 python python-3.x

我有一个 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/

相关文章:

python - 从字符串列表中提取 8 位数字

python - 鸭子类型(duck typing)实践 - Python 3.7

python - pip3 psutil无法安装较新版本

Python:一个程序来查找给定列表中最长运行的长度?

python - 从 pandas.DataFrame 中删除所有重复项的更好策略?

python - 惰性 ='joined' 是否意味着急切加载?

python - 事前评估-IndexError : index 0 is out of bounds for axis 0 with size 0

python - 无法从 Python3 打开到 PostgreSQL 的连接

python-3.x - 如何在 Django 中进行计算外键对象的查询?

python - Linkedin Luminol 异常检测和关联库的工作示例