为什么这个函数returnNone?

Why does this function return None?

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

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

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

if c == list: 正在检查 c 是否是 typelist 如果 if i > a and i < b: 永远不会评估为 True 你永远不会到达你的 return 声明因此默认 return None 因为所有 python 函数都没有指定 return 值,我想你想要这样的东西:

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 

可以简化为:

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

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

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

如果你想分开:

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 # 

然后解压:

new, inds = azimuth(10, 300, Az)

函数中的第一个if正在检查c是否是内置类型list

>>> list
<type 'list'>

因此检查不会为真,并且永远不会达到 return new。 在这种情况下,该函数将 return 默认值 None

要检查某物是否为列表,请使用 isinstance:

>>> c = [1,2,3]
>>> c == list
False
>>> isinstance(c, list)
True