地图,循环和列表推导问题

时间:2015-03-09 19:00:06

标签: python list dictionary

kn = input().split(" ")
n = int(kn[0])
k = int(kn[1])
niz = list(map(int, input().split(" ")))
newlis = []   
def rad(o):   
    return sum(niz[num:(num+k+o)])/(k+o)   
def posao(k):   
    return max(list(map(rad, range(0, n-k))))
for num in range(len(niz[0:(n-k+1)])):
    newlis.append(max(list(map(rad, range(0, n-num))))) 
#newlis = [max(list(map(rad, range(0, n-num)))) for num in range(len(niz[0:(n-k+1)]))]
print(max(newlis))

所以我使用了for循环,现在我想使用注释掉的列表理解(甚至是map())来加快它的速度。问题是,当我使用它时,它会一直返回num is not defined。我完全清楚代码是非常混乱和不洁,但如果有人能告诉我这里出错了,我会很感激。我只是python的初学者。

1 个答案:

答案 0 :(得分:-1)

def rad(o):   
    return sum(niz[num:(num+k+o)])/(k+o)  // I guess the problem should 
   // be here... as ^ num is not defined in this function and neither it is a global variable

尝试传递num作为参数

def rad(o,num):   
    return sum(niz[num:(num+k+o)])/(k+o)
newlis = [max([rad(x, num) for x in range(0, n-num)]) for num in range(len(niz[0:(n-k+1)]))]