从列表中删除初始值

时间:2013-11-08 22:04:07

标签: python list

嗨我有一个计算移动平均线的功能给出一个列表。这是代码:

def calculate(self, alist, days=2):

    averages = []
    signals  = []
    prices   = [float(n) for n in alist[1::2]]
    window   = collections.deque(maxlen=days)

    for price in prices:
        window.append(price)
        averages.append(0.00)
        signals.append("")
        if len(window) == days:
            mavg = sum(window) / days
            averages[-1] = mavg
            if price < mavg:
                signals[-1] = "SELL"
            elif price > mavg:
                signals[-1] = "BUY"

    averages[:] = ("%.2f" % avg for avg in averages)

    return averages, signals

它提供以下输出:

DATE            CLOSING        INDICATOR        SIGNAL
2013-10-01      887.00         0.00                                 
2013-10-02      887.99         0.00                                 
2013-10-03      876.09         0.00                                 
2013-10-04      872.35         0.00                                 
2013-10-07      865.74         877.83           SELL                
2013-10-08      853.67         871.17           SELL

有没有办法可以从打印中删除初始0,以便我的输出看起来像:

DATE            CLOSING        INDICATOR        SIGNAL
2013-10-01      887.00                                         
2013-10-02      887.99                                          
2013-10-03      876.09                                          
2013-10-04      872.35                                          
2013-10-07      865.74         877.83           SELL                
2013-10-08      853.67         871.17           SELL 

1 个答案:

答案 0 :(得分:1)

尝试:

def calculate(self, alist, days=2):

    # rest of your functions

    tol=0.01
    averages[:] = ("%.2f" % avg if abs(avg)>=tol else ' '  for avg in averages)

    return averages, signals