【发布时间】:2021-04-09 16:34:50
【问题描述】:
您好,这是我第一次发帖,所以我希望我添加所有需要的细节。我目前在 Al Sweigart 编写的 Automate The Boring Stuff With Python 的第 4 章中。
在 Conway 的生命游戏项目中,我在得到 20 行输出后遇到了错误。我从第 63 行和第 66 行得到 2 个错误中的 1 个。
# Conway's Game of Life
import random, time, copy
WIDTH = 60
HEIGHT = 20
# Create a list of list for the cells
next_cells = []
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
next_cells.append(column) # next_cells is a list of column lists
# Start of main loop
while True:
print('\n\n\n\n\n') # Separate each step with newlines
current_cells = copy.deepcopy(next_cells)
# Print current_cells on the screen
for y in range(HEIGHT):
for x in range(WIDTH):
print(current_cells[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 left_coord is always between 0 and WIDTH - 1
left_coord = (x - 1) % WIDTH
right_coord = (x + 1) % WIDTH
above_coord = (y - 1) % HEIGHT
below_coord = (y + 1) % HEIGHT
# Count number of living neighbors
num_neighbors = 0
if current_cells[left_coord][above_coord] == '#':
num_neighbors += 1 # Top left neighbor is alive
if current_cells[x][above_coord] == '#':
num_neighbors += 1 # Top neighbor is alive
if current_cells[right_coord][above_coord] == '#':
num_neighbors += 1 # Top right neighbor is alive
if current_cells[left_coord][y] == '#':
num_neighbors += 1 # Left neighbor is alive
if current_cells[right_coord][y] == '#':
num_neighbors += 1 # Right neighbor is alive
if current_cells[left_coord][below_coord] == '#':
num_neighbors += 1 # Bottom left neighbor is alive
if current_cells[x][below_coord] == '#':
num_neighbors += 1 # Bottom neighbor is alive
if current_cells[right_coord][below_coord] == '#':
num_neighbors += 1 # Bottom right neighbor is alive
# Set cell based on Conway's Game of Life rules
if current_cells[x][y] == '#' and (num_neighbors == 2 or num_neighbors == 3):
# Living cells with 2 or 3 neighbors stay alive
next_cells = '#'
elif current_cells[x][y] == ' ' and num_neighbors == 3:
# Dead cells with 3 nighbors become alive
next_cells[x][y] = '#'
else:
# Everything else dies or stays dead
next_cells[x][y] = ' '
time.sleep(1) # Add a 1-second pause to reduce flickering
第 63 行产生 - next_cells[x][y] = '#' TypeError: 'str' 对象不支持项目分配
第 66 行产生 - next_cells[x][y] = ' ' TypeError: 'str' 对象不支持项目分配
奇怪的是,next_cells 在第 7 行被定义为一个列表。我每次都在循环结束时打印它以确保它保持为一个列表。我还检查了缩进问题,这些问题我确实纠正了,但如前所述,稍后在程序中仍然出现错误。我还查找了与此类似的其他问题,但据我所知,没有什么与我的问题足够接近。
我对编程并不陌生,但我仍然缺乏很多知识,因此非常感谢任何类型的帮助!
谢谢。
【问题讨论】:
-
我认为这是因为您在第 60 行将
next_cells定义为字符串 -
就是这样!哇,这表明错过这样的事情是多么容易,谢谢。
标签: python string list typeerror