返回'通过'通过方法python迭代

时间:2017-01-24 22:06:19

标签: python python-2.7

是否有任何pythonic方式返回'通道'从这样的方法迭代:

import numpy as np

x = [1, 2, np.nan, 4]

for q in x:

    if np.isnan(q):
        pass
    else:
        print q
1
2
4

我正在努力实现(在更复杂的代码中)类似的东西:

import numpy as np
x = [1, 2, np.nan, 4]

def skip(var):
    if np.isnan(var):
        return pass
    else:
        return var

for q in x:
    var(q)
    print q

任何方式使这项工作?通过方法传递迭代?

5 个答案:

答案 0 :(得分:2)

你不能返回pass,但你可以return隐式return None然后你可以在调用代码中使用None来检查它是否被传递。

答案 1 :(得分:1)

您只需要将方法skip中的标志传递给for循环。没有办法传球。

正如其他人所说,return隐式返回None。

由于您没有改变变量,因此在if块中运行函数后嵌套循环的一部分是安全的。

def skip(var):
    if not np.isnan(var):
        return var

for q in x:
    if var(q):
        print q

答案 2 :(得分:1)

为什么不使用<form action="process.php" method="post"> <style> td{ border: 1px solid black; } </style> <input type="hidden" name="formID" value= "demo" /> <table> <tr> <td> <br> <b>Email Address </><input type="text" name="address[]" /> <input type="checkbox" name="morningcheck[]" value="morningcheck"> Morning Checks <input type="checkbox" name="outages[]" value="outages"> Outages <input type="checkbox" name="maintenance[]" value="maintenance"> Maintenance<br> <br> </td> </tr> <table> <table> <tr> <td> <br> <b>Email Address </><input type="text" name="address[]" placeholder= "Email address 1" /> <input type="checkbox" name="morningcheck[]" value="morningcheck"> Morning Checks <input type="checkbox" name="outages[]" value="outages"> Outages <input type="checkbox" name="maintenance[]" value="maintenance"> Maintenance<br> <br> </td> </tr> </table> <br> <input type="submit" value="Subscribe" name="add"/> <input type="submit" value="Unsubscribe" name="delete"/> </form>'

filter

for q in filter(lambda z: not np.isnan(z), x): # put the rest of your code here print q 相当pythonic和轻量级,并确保你的循环块只需要担心积极的情况。

答案 3 :(得分:0)

def skip(var):
    if np.isnan(var):
        return None
    else:
        return var

for q in x:
    result = skip(q)
    if result != None:
         var(result)
    print q

答案 4 :(得分:0)

我知道有多个答案,但我发现continue正是我所寻找的那样:

将numpy导入为np

x = [1, 2, np.nan, 4]

def skip(var):
    return np.isnan(var)


for q in x:
    if skip(q)
       continue
    print q