【发布时间】:2020-05-06 16:02:29
【问题描述】:
我正在阅读“用 python 自动化无聊的东西”这本书,无法理解使用 % 运算符的简单表达式。表达式是leftCoord = (x - 1) % WIDTH,在循环的第一次迭代中计算为(0 - 1) % 60。在我看来,% 运算符应该评估为除法的其余部分。为什么它评估为 9?
这是程序中出现问题的表达式之前的部分:
import random,time,copy
WIDTH = 60
HEIGHT = 20
# Create a list of list for the cells:
nextCells = []
for x in range(WIDTH):
column = [] # Create a new column.
for y in range(HEIGHT):
if random.randint(0,1) == 0:
column.append('#') # Add a living cell.
else:
column.append(' ') # Add a dead cell.
nextCells.append(column) # nextCells is a list of column lists.
while True: # Main program loop.
print('\n\n\n\n\n') # Separate each step with newlines.
currentCells = copy.deepcopy(nextCells)
# Print currentCells on the screen:
for y in range(HEIGHT):
for x in range(WIDTH):
print(currentCells[x][y], end='') # Print the # or space.
print() # Print a newline at the end of the row.
# Calculate the next step's cells based on current step's cells:
for x in range(WIDTH):
for y in range(HEIGHT):
# Get neighboring coordinates:
# % WIDTH ensures leftCoord is always between 0 and WIDTH -1
leftCoord = (x - 1) % WIDTH
rightCoord = (x + 1) % WIDTH
aboveCoord = (y - 1) % HEIGHT
belowCoord = (y + 1) % HEIGHT
【问题讨论】:
-
这需要更多上下文。这不是一个完整的陈述,所以希望你把它从更长的表达式中提取出来。
标签: python-3.x modulus