检查嵌套列表是否在特定索引处具有和不具有值的优雅方法是什么?
what is the elegant way to check if a nested list has and has NOT a value at a specific index?
假设我们有二维数组:
ar = [[1,2],
[3,4]]
if ar[1][1]:
#works
if not ar[3][4]:
#breaks!!
因为我是python的新手,所以需要知道什么是优雅的语法。
Python 非常喜欢的 EAFP 异常处理方法将是我的做法。
try:
print(ar[i][j]) # i -> row index, j -> col index
except IndexError:
print('Error!')
另一种方法,也称为 LYBL 方法,将使用 if
检查:
if i < len(ar) and j < len(ar[i]):
print(ar[i][j])
这里是 "one liner" 版本(这会降低可读性,但你似乎想要):
print(ar[i][j] if i < len(ar) and j < len(ar[i]) else "Error")
- What is the EAFP principle in Python?
- LBYL vs EAFP in Java?(相同的概念几乎适用于任何语言。)
如果这是您需要经常执行的检查,您可以自己编写一个小辅助函数,以便您的主要代码更流畅:
def has_item_at(items, i, j):
return i < len(items) and j < len(items[i])
def main():
items = [[1, 2], [3, 4]]
if has_item_at(items, 1, 1):
# do stuff
if has_item_at(items, 3, 4):
# don't do stuff
如果您需要检查是否存在并检索该项目,您可以改为执行以下操作:
def get_item(items, i, j, default=None):
if i < len(items) and j < len(items[i]):
return items[i][j]
return default
def main():
items = [[1, 2], [3, 4]]
item = get_item(items, 1, 1)
if item is not None:
# do stuff
假设我们有二维数组:
ar = [[1,2],
[3,4]]
if ar[1][1]:
#works
if not ar[3][4]:
#breaks!!
因为我是python的新手,所以需要知道什么是优雅的语法。
Python 非常喜欢的 EAFP 异常处理方法将是我的做法。
try:
print(ar[i][j]) # i -> row index, j -> col index
except IndexError:
print('Error!')
另一种方法,也称为 LYBL 方法,将使用 if
检查:
if i < len(ar) and j < len(ar[i]):
print(ar[i][j])
这里是 "one liner" 版本(这会降低可读性,但你似乎想要):
print(ar[i][j] if i < len(ar) and j < len(ar[i]) else "Error")
- What is the EAFP principle in Python?
- LBYL vs EAFP in Java?(相同的概念几乎适用于任何语言。)
如果这是您需要经常执行的检查,您可以自己编写一个小辅助函数,以便您的主要代码更流畅:
def has_item_at(items, i, j):
return i < len(items) and j < len(items[i])
def main():
items = [[1, 2], [3, 4]]
if has_item_at(items, 1, 1):
# do stuff
if has_item_at(items, 3, 4):
# don't do stuff
如果您需要检查是否存在并检索该项目,您可以改为执行以下操作:
def get_item(items, i, j, default=None):
if i < len(items) and j < len(items[i]):
return items[i][j]
return default
def main():
items = [[1, 2], [3, 4]]
item = get_item(items, 1, 1)
if item is not None:
# do stuff