在python list comprehension中打印(或执行语句)

时间:2014-03-26 02:33:40

标签: python list-comprehension

我想知道是否有任何方法可以在列表理解中打印(或者更常见的是执行语句)。
所以我们都在同一页面上,考虑以下函数中的列表理解,f:

def g(x):
     return some_complicated_condition_function(x)

def f(list_of_numbers,n):
     return [i for i in range(n) if g(list_of_numbers[i]) > 0]

说我在调用f时遇到一些神秘的错误,并希望通过使用类似的东西来捕获错误进行调试:

try: g(list_of_numbers[i])
except: 
    print (i,list_of_numbers[i]))
    raise Exception("Danger Will Robinson!")

有没有这样做而不重写我的列表理解作为传统的for / while循环?

谢谢! 附:也许这是一种可怕的调试方式(我是数学,而不是CS),所以如果你有任何提示,请不要害羞。

1 个答案:

答案 0 :(得分:1)

哎呀,所以我发布后就意识到了答案! >:o

我只需要制作另一个功能:

def h(i,list_of_numbers):
    try: g(list_of_numbers[i])
    except: 
        print (i,list_of_numbers[i]))
        raise Exception("Danger Will Robinson!")
return i

然后我可以让我的列表理解:

[h(i) for i in range(n) if g(list_of_numbers[i]) > 0]

...我想这种技术应该适用于执行我想要的任何语句。 Darn,我很高兴最终能在堆栈交换上发布一些内容!