gpt4 book ai didi

python - 我应该如何将 try/except 放在一行中?

转载 作者:IT老高 更新时间:2023-10-28 21:40:23 27 4
gpt4 key购买 nike

在 python 中有没有办法将 try/except 变成单行?

类似...

b = 'some variable'
a = c | b #try statement goes here

其中 b 是已声明的变量,而 c 不是...所以 c 会抛出错误而 a 会变成 b...

最佳答案

在 python3 中你可以使用 contextlib.suppress :

from contextlib import suppress

d = {}
with suppress(KeyError): d['foo']

关于python - 我应该如何将 try/except 放在一行中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2524853/

27 4 0