【问题标题】:Count number of times the numbers are increasing in Python list计算 Python 列表中数字增加的次数
【发布时间】:2021-12-01 05:20:49
【问题描述】:

我有这个数字列表:{199, 200, 208, 210, 200, 207, 240}。

  1. 我想确定列表中的数字是如何增加或减少的。例如,在 199 之后,我有 200,即相差 1。但在 200 之后,我有 208,即相差 8。如何确定 Python 中整个列表的增加/减少量度?

  2. 其次,我想计算数字增加了多少次。由于列表由增加和减少的数字组成,我只想计算它增加了多少次。

谢谢。

【问题讨论】:

    标签: python python-3.x list


    【解决方案1】:

    您可以使用 zip() 将元素与其后继元素配对并在列表推导中处理它们:

    numbers = [199, 200, 208, 210, 200, 207, 240]
    
    increments = [b-a for a,b in zip(numbers,numbers[1:]) if b>a]
    decrements = [b-a for a,b in zip(numbers,numbers[1:]) if a>b]
    
    print(increments)      # [1, 8, 2, 7, 33]
    print(decrements)      # [-10]
    print(len(increments)) # 5
    

    您也可以直接获取递增对的数量(无需构建递增列表):

    sum(b>a for a,b in zip(numbers,numbers[1:]))  # 5
    

    【讨论】:

    • 谢谢 :) 它有效。如果我想计算有多少测量值比之前的测量值大怎么办?在此示例中,有 7 个测量值大于之前的测量值。
    • 如果预期结果是 7,我不确定您所说的“大于前一个测量值”是什么意思。只有 5 个测量值大于其前身(如我的示例所示)。
    【解决方案2】:

    解决您的问题 #1,您可以计算随着 x 值增加的 Spearmans 相关性。它的值在 [-1, 1] 范围内,如果值为正,则 y 随着 x 的增加而增加,如果值为负,则 y 随着 x 的增加而减小,如果值为 0,则没有相关性。如果值很高,接近 1 或 -1,则强烈表明这两个数据高度相关。因此,即使您不绘制数据,您也可以通过了解 Spearmans 值来判断趋势是正数还是负数或没有关系。

    代码

    from scipy.stats import spearmanr
    import matplotlib.pyplot as plt
    
    
    y = [199, 200, 208, 210, 200, 207, 240]
    x = range(len(y))
    
    # calculate spearman's correlation
    corr, _ = spearmanr(x, y)
    print('Spearmans correlation: %.3f' % corr)
    
    plt.plot(x, y, '--*')
    plt.savefig('corr.png')
    plt.show()
    

    输出

    Spearmans correlation: 0.667
    

    参考文献

    【讨论】:

      【解决方案3】:
      l = [199,200,208,210,200,207,240]
      
      diff = [l[i+1] - l[i] for i in range(len(l) - 1)]
      
      # count the number of increasing changes
      num_inc = sum([l[i+1] > l[i] for i in range(len(l) - 1)]) # 5
      

      【讨论】:

      • 另外,第二行不需要方括号sum(l[i+1] > l[i] for i in range(len(l)))
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-04
      • 2017-10-06
      • 2017-03-08
      • 2014-08-22
      • 2021-07-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多