Dra*_*ght 2 python exception-handling list nested-lists
假设我们有2d数组:
ar = [[1,2],
[3,4]]
if ar[1][1]:
#works
if not ar[3][4]:
#breaks!!
Run Code Online (Sandbox Code Playgroud)
因为我是python的新手,需要知道什么是优雅的语法.
Python非常受欢迎的EAFP方法与异常处理将是我的方式.
try:
print(ar[i][j]) # i -> row index, j -> col index
except IndexError:
print('Error!')
Run Code Online (Sandbox Code Playgroud)
另一种方法,也称为LYBL方法,将使用if检查:
if i < len(ar) and j < len(ar[i]):
print(ar[i][j])
Run Code Online (Sandbox Code Playgroud)
这里是"一线"版本(杀死可读性,但你似乎想要):
print(ar[i][j] if i < len(ar) and j < len(ar[i]) else "Error")
Run Code Online (Sandbox Code Playgroud)