python - 找到一个函数来查找列表中相邻值之间的差异,然后针对阈值进行测试

标签 python for-loop python-3.x average

所以基本上我需要一个函数来计算列表中每个值之间的差异,然后针对阈值进行测试。如果两个相邻数字之间的差异大于给定的阈值,则应将这两个数字之间的平均值依次插入到列表中。如果差异不大于则应返回原始列表。最多只能插入一个数字。

我有

def test(list, Threshold):

for i in range(len(list)): 

         if abs((list[i] - list[i+1])) > Threshold : 
               ((list[i] + list[i+1])/2) 
               (list.append((list[i] + list[i+1])/2)) 
               ( list.sort()) 
         else: 
               ( list) 

Z = [1,2,4,4.5] 

test(Z,1.5) 

Z = [1,2,3.0,4,4.5]

这是唯一可行的方案。如果没有一个超过阈值,或者有两个倍数超过阈值,则不起作用。我知道我正朝着正确的方向前进

最佳答案

当您附加新数字时,只需break即可。以下是您的函数的编辑版本。另请注意,我已经调整了 for 循环的范围以防止索引错误。比较 list[i]list[i+1] 时,i+1 不能大于列表大小,因此 i 必须停在 len(list)-1

def test(list, Threshold):

    for i in range(len(list)-1):    # <-- note the change in limit

        if abs(list[i] - list[i+1]) > Threshold:
            list.append((list[i] + list[i+1])/2) 
            list.sort()
            break    # this will stop the loop

已测试

z = [1,2,4,4.5]
test(z,1.5)
z
[1, 2, 3, 4, 4.5]

关于python - 找到一个函数来查找列表中相邻值之间的差异,然后针对阈值进行测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19712748/

相关文章:

python - 如何使用鼠标单击通过OpenCV和Python更改变量?

python - 如何计算两个相似的 pandas 列之间的索引交集?

python - 计算按前两列中的索引分组的 numpy 数组条目的第 N 列的总和?

python - 在 Python 环境下使用 Pygame 和 OpenGL 绘制立方体

javascript - 在 JS 中使用 For 循环追加 li 项

r - 如何计算R中的合并标准差?

linux - 多次重复文本

python - 使用 numpy 获取切片后剩余的内容

python - haystack ElasticsearchDocumentStore 无法连接 Elasticsearch

python - Pandas 自合并阻塞了缺失的结构