为什么这个函数返回 None?

nad*_*v_n -1 python python-2.x

我的函数总是返回None,这是怎么回事?

Az= [5,4,25.2,685.8,435,2,8,89.3,3,794]
new = []

def azimuth(a,b,c):
 if c == list:
    for i in c:
       if i > a and i < b:
           new.append(i)
           return new

d=azimuth(10,300,Az)
print d
Run Code Online (Sandbox Code Playgroud)

此外,如果有人知道如何将这些数字的位置提取到不同的列表中,那将非常有帮助。

Pad*_*ham 5

if c == list:正在检查 if cis a typeie alist也是 if if i > a and i < b:never 评估为True 您将永远不会到达您的 return 语句,因此默认情况下,return None因为所有 python 函数都没有指定返回值,我想您想要类似的东西:

Az = [5,4,25.2,685.8,435,2,8,89.3,3,794]

def azimuth(a,b,c):
  new = []
  if isinstance(c ,list):
     for i in c:
        if  a < i < b:
           new.append(i)
  return new # return outside the loop unless you only want the first 
Run Code Online (Sandbox Code Playgroud)

可以简化为:

def azimuth(a, b, c):
    if isinstance(c, list):
        return [i for i in c if a < i < b]
    return [] # if  c is not a list return empty list
Run Code Online (Sandbox Code Playgroud)

如果您也想要索引,请使用enumerate

def azimuth(a, b, c):
    if isinstance(c, list):
        return [(ind,i) for i, ind in enumerate(c) if a < i < b]
    return []
Run Code Online (Sandbox Code Playgroud)

如果你想要它们分开:

def azimuth(a,b,c):
  inds, new = [], []
  if isinstance(c ,list):
     for ind, i in enumerate(c):
        if  a < i < b:
           new.append(i)
           inds.append(ind)
  return new,inds # 
Run Code Online (Sandbox Code Playgroud)

然后解压:

new, inds = azimuth(10, 300, Az)
Run Code Online (Sandbox Code Playgroud)