要打印代码列表?

时间:2013-08-21 07:31:42

标签: python list

sub = [767220, 769287, 770167, 770276, 770791, 770835, 771926, 1196500, 1199789,1201485, 1206331, 1206467, 1210929, 1213184, 1213204, 1213221, 1361867, 1361921, 1361949, 1364886, 1367224, 1368005, 1368456, 1368982, 1369000, 1370365, 1370434, 1370551, 1371492, 1471407, 1709408, 1710264, 1710308, 1710322, 1710350, 1710365, 1710375]

def runningMean(seq, n=0, total=0): #function called recursively
    if not seq:
        return []
    total = total + int(seq[-1])
    if int(seq[-1]) < total/float(n+1) * 0.9:  # Check your condition to see if it's time to stop averaging.
        return []
    return runningMean(seq[:-1], n=n+1, total=total) + [total/float(n+1)]

avg = runningMean(sub, n = 0, total = 0)
print avg #it prints the avg value which satisfies the above condition

获得的结果是:

[1710198.857142857, 1710330.6666666667, 1710344.0, 1710353.0, 1710363.3333333333, 1710370.0, 1710375.0]

但现在我需要打印平均值和&amp;满足条件的子列表(列表子中的项目大于avg中的项目因此它打印avg现在我需要它来打印seq中的项目)

[1710198.857142857, 1710330.6666666667, 1710344.0, 1710353.0, 1710363.3333333333, 1710370.0, 1710375.0]
[1709408, 1710264, 1710308, 1710322, 1710350, 1710365, 1710375]

如何更改将在Python中为我提供此类结果的代码?

2 个答案:

答案 0 :(得分:1)

试试这个:

sub = [767220, 769287, 770167, 770276, 770791, 770835, 771926, 1196500, 1199789,1201485, 1206331, 1206467, 1210929, 1213184, 1213204, 1213221, 1361867, 1361921, 1361949, 1364886, 1367224, 1368005, 1368456, 1368982, 1369000, 1370365, 1370434, 1370551, 1371492, 1471407, 1709408, 1710264, 1710308, 1710322, 1710350, 1710365, 1710375]
def runningMean(seq, n=0, total=0): #function called recursively
    L = [[],[]]
    if len(seq) == 0:
        return L
    total = total + int(seq[-1])
    if int(seq[-1]) < total/float(n+1) * 0.9:  # Check your condition to see if it's time to stop averaging.
        return L
    NL = runningMean(seq[:-1], n=n+1, total=total)
    L[0] += NL[0] + [total/float(n+1)]
    L[1] += [seq[-1]] + NL[1]
    return L

avg = runningMean(sub, 0, 0)
print(avg[0])
print(avg[1])

输出:

[1710198.857142857, 1710330.6666666667, 1710344.0, 1710353.0, 1710363.3333333333, 1710370.0, 1710375.0]
[1710375, 1710365, 1710350, 1710322, 1710308, 1710264, 1709408]

答案 1 :(得分:0)

Python可以从方法中return multiple values。您可以使用它在每次调用时返回您感兴趣的元素。