【发布时间】:2021-03-12 14:54:36
【问题描述】:
我正在尝试清理我的 if 语句,我们正在做一个小组项目,我的同行说这段代码看起来太混乱了。请给我一些关于缩短或清理它的提示,代码目前看起来像这样;
for r in range(n):
for col in range(n):
# Skip, if it contains a mine
if numbers[r][col] == -1:
continue
# Check up
if r > 0 and numbers[r-1][col] == -1:
numbers[r][col] = numbers[r][col] + 1
# Check down
if r < n-1 and numbers[r+1][col] == -1:
numbers[r][col] = numbers[r][col] + 1
# Check left
if col > 0 and numbers[r][col-1] == -1:
numbers[r] = numbers[r] + 1
# Check right
if col < n-1 and numbers[r][col+1] == -1:
numbers[r][col] = numbers[r][col] + 1
# Check top-left
if r > 0 and col > 0 and numbers[r-1][col-1] == -1:
numbers[r][col] = numbers[r][col] + 1
# Check top-right
if r > 0 and col < n-1 and numbers[r-1][col+1]== -1:
numbers[r][col] = numbers[r][col] + 1
# Check below-left
if r < n-1 and col > 0 and numbers[r+1][col-1]== -1:
numbers[r][col] = numbers[r][col] + 1
# Check below-right
if r < n-1 and col< n-1 and numbers[r+1][col+1]==-1:
numbers[r][col] = numbers[r][col] + 1
【问题讨论】:
标签: python-3.x if-statement code-cleanup