【问题标题】:ATBS with Python - Error with Conway's Game of LifeATBS with Python - Conway 的生命游戏出错
【发布时间】: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


【解决方案1】:

我尝试在这段代码上运行mypy(一个静态类型检查器,您可以在http://mypy-lang.org/ 阅读),预感它会揭示问题,果然:

gol.py:60: error: Incompatible types in assignment (expression has type "str", variable has type "List[List[str]]")

这是完全正确的;它告诉您您已将 next_cells 定义为列表列表,并且您正在用字符串覆盖它:

                next_cells = '#'

【讨论】:

  • 你是对的。也感谢您的参考,我将阅读有关 mypy 的信息。
【解决方案2】:

在第 60 行,您指定 next_cells = '#',它将 next_cells 转换为 str。 稍后您尝试分配next_cells[x][y] = '#',此时next_cells 不是列表而是str。

每当第一个 if 语句触发时,它会将 next_cells 列表转换为 str 对象,并在下次运行任何其他 elif 语句时导致错误。

【讨论】:

  • 你是对的!亨利也提到了这一点。你们很快,谢谢。
猜你喜欢
  • 1970-01-01
  • 2013-12-01
  • 2016-04-05
  • 2023-02-08
  • 1970-01-01
  • 1970-01-01
  • 2018-01-12
  • 2017-03-09
  • 2018-07-11
相关资源
最近更新 更多