Sco*_*y1- 4 python if-statement
在python中是否可能直接在三元语句中引发错误?
如:
import numpy as np
y = np.random.rand(200, 5, 5)
y = (y[:, None] if y.ndim == 1
else y if y.ndim == 2
else raise ValueError('`y` must be given as a 1D or 2D array.'))
Run Code Online (Sandbox Code Playgroud)
当然,可以使用简单的if / elif / else语句来完成此操作。因此,我专门要求使用“单行”三元语句的解决方案。
只是为了澄清:
我知道三元语句无意引起错误,并且根据PEP8等,它也不是很好的样式。我只是在问是否有可能。