【问题标题】:How to calculate the average length of time in a list如何计算列表中的平均时间长度
【发布时间】:2017-02-16 19:40:39
【问题描述】:

我想弄清楚价格平均保持在一定范围内的时间。假设我的价值观是:

[10, 7.7, 9.5, 15, 8.8, 9.3, 7.7, 16]

例如,当值在 8 到 9.9 之间时,平均多长时间后才大于 14(不倒退)?

9.5 在 1 天内通过 14。 3天8.8。 2天内9.3。 1天7.7。所以平均值是 (1 + 3 + 2 + 1 )/4 = 1.75 天。

我正在尝试创建一个为我执行该计算的程序,但我遇到了问题。

代码:

list = [10, 7.7, 9.5, 15, 8.8, 9.3, 7.7, 16] 

def new_function()
    for i in list:

    while 8 < x < 9.99 (store index position as initial y);

    when x becomes > 14 (take index position and subtract it from initial   y to find length) 

    repeat for next i where  8 < x < 9.9

average = sum(length)/len(length)
print(average)

【问题讨论】:

  • 能否提供一个csv文件中的数据样本(10行左右)?这将使您更容易理解您的要求并帮助验证推荐的解决方案。
  • 这些数字与我在列表中提供的值非常相似。我只是用这些数字来简化事情。 2 列:日期和价格。数千行数据。感谢您的帮助

标签: python csv


【解决方案1】:

一旦找到起始条目,就在列表中为每个条目保留一个计数器,直到找到一个 &gt; 14。此时将找到的值添加到总数中并重置运行。每次循环时还要为每个计数器添加一个,如下所示:

data = [10, 7.7, 9.5, 15, 8.8, 9.3, 7.7, 16]
run = []
total_days = 0
total_entries = 0

for value in data:
    if value > 14:
        total_days += sum(run)
        total_entries += len(run)
        run = []
    elif 8 < value < 9.99 or len(run):
        run.append(0)
    run = [value + 1 for value in run]

print total_days / float(total_entries)

给你:

1.75

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多