gpt4 book ai didi

python - 在 python 列表理解中打印(或执行语句)

转载 作者:行者123 更新时间:2023-11-28 18:44:02 25 4
gpt4 key购买 nike

我想知道是否有任何方法可以在列表理解中打印(或者更一般地说,执行语句)。
所以我们都在同一个页面上,考虑以下函数 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),所以如果您有任何提示,请不要害羞。

最佳答案

哎呀,所以我发布后才知道这个问题的答案! >:哦

我只需要做另一个功能:

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]

...而且我想该技术应该适用于执行我想要的任何语句。该死的,我很兴奋终于可以在堆栈交换上发布一些东西了!

关于python - 在 python 列表理解中打印(或执行语句),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22650419/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com