简体   繁体   English

映射问题,用于循环和列表理解

[英]Issue with maps, for loops and list comprehensions

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))

So I've got this working with a for loop and now I want to use the commented out list comprehension (or even map() ) to make it faster. 因此,我已经使用了for循环,现在我想使用注释掉的列表推导(甚至map() )来使其更快。 Problem is, it keeps returning that num is not defined when I use either. 问题是,当我使用任何一个时,它总是返回num is not defined I'm completely aware the code is very messy and unclean, but if someone could tell me where I'm going wrong with this, I'd appreciate it. 我完全知道代码很乱而且很脏,但是如果有人可以告诉我我在哪里出错了,我将不胜感激。 I'm only a beginner with python. 我只是python的初学者。

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

Try passing num as argument 尝试将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)]))]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM