检查位置是否存在于嵌套列表中
Checking If Position Exists in Nested List
我正在尝试解决 Python 编码问题。给定一个仅包含 1 和 0 的特定数组,我必须编写一个程序,该程序 returns 一个数组遵循一些规则:
- 每个1必须换成9
- 每个 0 都必须用其周围(上、下、左、右)中 1 的数量替换
我遇到了棱角问题,因为我必须先检查某个位置是否存在,然后再检查它是否为1。我现在的解决方案是使用8 'if' 语句,但它看起来很丑陋并且似乎效率低下:
counter = 0
if x+1 < len(board):
if board[x+1][y] == 9:
counter += 1
if y+1 < len(board[i]):
if board[x][y+1] == 9:
counter += 1
if x-1 >= 0:
if board[x-1][y] == 9:
counter += 1
if y-1 >= 0:
if board[x][y-1] == 9:
counter += 1
board[x][y] = counter
虽然它确实有效,但我想知道是否有 easier/cleaner 我可以实施的解决方案。
一种方法是使用逻辑短路:
if x+1 < len(board) and board[x+1][y] == 9:
counter += 1
如果第一个子句是 False
,则根本不会计算第二个子句。您不会遇到该异常。
接下来你可以简化数学:利用 class bool
是从 int
派生的事实: False
是 0; True
是 1。
counter += x+1 < len(board) and board[x+1][y] == 9
现在,您可以将所有四个留置权放在一行中,甚至可以将所有四个布尔表达式组合成一个 +=
语句。
我不清楚该代码片段如何适合您的解决方案,但如果您的问题是邻域迭代,一个常见的技巧是预定义偏移量:
...
# suppose the current position is (x,y)
for dx, dy in [(1, 0), (0, 1), (-1, 0), (0, -1)]:
tx = x + dx # t as in target
ty = y + dy
if 0 <= tx < len(board) and 0 <= ty < len(board[tx]):
# the position (tx, ty) exists, do whatever you want with it
pass
我正在尝试解决 Python 编码问题。给定一个仅包含 1 和 0 的特定数组,我必须编写一个程序,该程序 returns 一个数组遵循一些规则:
- 每个1必须换成9
- 每个 0 都必须用其周围(上、下、左、右)中 1 的数量替换
我遇到了棱角问题,因为我必须先检查某个位置是否存在,然后再检查它是否为1。我现在的解决方案是使用8 'if' 语句,但它看起来很丑陋并且似乎效率低下:
counter = 0
if x+1 < len(board):
if board[x+1][y] == 9:
counter += 1
if y+1 < len(board[i]):
if board[x][y+1] == 9:
counter += 1
if x-1 >= 0:
if board[x-1][y] == 9:
counter += 1
if y-1 >= 0:
if board[x][y-1] == 9:
counter += 1
board[x][y] = counter
虽然它确实有效,但我想知道是否有 easier/cleaner 我可以实施的解决方案。
一种方法是使用逻辑短路:
if x+1 < len(board) and board[x+1][y] == 9:
counter += 1
如果第一个子句是 False
,则根本不会计算第二个子句。您不会遇到该异常。
接下来你可以简化数学:利用 class bool
是从 int
派生的事实: False
是 0; True
是 1。
counter += x+1 < len(board) and board[x+1][y] == 9
现在,您可以将所有四个留置权放在一行中,甚至可以将所有四个布尔表达式组合成一个 +=
语句。
我不清楚该代码片段如何适合您的解决方案,但如果您的问题是邻域迭代,一个常见的技巧是预定义偏移量:
...
# suppose the current position is (x,y)
for dx, dy in [(1, 0), (0, 1), (-1, 0), (0, -1)]:
tx = x + dx # t as in target
ty = y + dy
if 0 <= tx < len(board) and 0 <= ty < len(board[tx]):
# the position (tx, ty) exists, do whatever you want with it
pass