首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >根据2d列表中的内容编辑2d列表

根据2d列表中的内容编辑2d列表
EN

Stack Overflow用户
提问于 2015-04-07 07:06:21
回答 2查看 193关注 0票数 0

对于家庭作业,我必须做一个基于文本的康威的生活游戏在蟒蛇。它的规则是这样。

任何活细胞如果少于两个活的邻居就会死

任何有两个或三个活邻居的活细胞都会活到下一代。

任何有三个以上活邻居的活细胞都会死。

任何有三个活邻居的死细胞都会变成活细胞。

我把棋盘放在一个2d的列表中,我很难找到如何循环列表中的每个元素(游戏中的每个单元,死或活,'0‘或'X'),并根据周围的单元格检查条件。

启动板的一个例子是

代码语言:javascript
复制
00000
00000
000X0
000X0
000X0

首先,我尝试遍历每个元素,并检查当前单元格右侧的单元格是否为X。

这是我做的代码,试着这样做。下一次迭代的函数应该是返回板和康威生命游戏的下一次迭代,但是现在,为了解决问题,我只想让它检查右边的单元格,如果右边的单元格是X的话。

代码语言:javascript
复制
def nextIteration(board):
    newBoardTemp = board[:]
    newBoard = [board[:] for board in newBoardTemp]
    column = 0
    for row in newBoard:
        column = 0
        for item in range(len(row)):
             column += 1
             item2 = row[column + 1]
             if item == item2:
                 board[item][column] = 'X'


def printBoard(board):
   for row in board:
       for item in row:
           print(item, end="")
       print()


def main():
    rows = input("Please enter number of rows: ")
    columns = input("Please enter number of columns: ")
    print()
    cellRow = 0
    cellRows = []
    cellColumns = []
    total = 0
    #the cellRow and cellColumn will contain all of the inputted rows           
    #and columns connected by the index value                                   
    while cellRow != "q":
        cellRow = input("Please enter the row of a cell to turn on (or q to exi\
t): ")
        if cellRow != "q":
                cellColumn = input("Please enter a column for that cell: ")
                cellRows.append(cellRow)
                cellColumns.append(cellColumn)
                total = total + 1
                print()
        else:
            print()
    board = []
    #boardTemp will hold a list that contains one row of the entire board       
    boardTemp = []
    for i in range(int(rows)):
        boardTemp.append("0")
    for i in range(int(columns)):
        board.append(boardTemp[:])
    for i in range(total):
        temp = i
        board[int(cellRows[temp - 1])][int(cellColumns[temp - 1])] = "X"
    iterations = input("How many iterations should I run? ")
 print()
    print("Starting Board:")
    print()
    printBoard(board)
    for i in range(int(iterations)):
        iterationNumber = 1
        nextIteration(board)
        print("Iteration", iterationNumber,":")
        printBoard(board)

main()

这是我在前面展示的启动板上遇到的错误。

代码语言:javascript
复制
File "hw7.py", line 9, in nextIteration
    item2 = row[column + 1]
IndexError: list index out of range
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-04-07 11:58:18

代码语言:javascript
复制
for item in range(len(row)):
    column += 1
    item2 = row[column + 1]
    if item == item2:
        board[item][column] = 'X'

在这个循环的第四次迭代中,您将item2设置为row5,这超出了范围。如果要比较两个相邻的单元格,则应在以后增加列(在第一个迭代项==行和item2 == row2中)。您还应该更早地停止循环。以下应有助于纠正您的错误:

代码语言:javascript
复制
for item in range(len(row) - 1):
    item2 = row[column + 1]
    if item == item2:
        board[item][column] = 'X'
    column += 1
票数 0
EN

Stack Overflow用户

发布于 2015-04-07 13:47:01

你想用边缘做什么?一种可能是把表面当作一个圆环,也就是甜甜圈.如果你不介意,请跟我来

代码语言:javascript
复制
nr = 5 ;  nc = 4
# here I define a List Of Lists with content unrelated to Conway's Life
# just to have an easy to follow example
lol = [["%d"%(r*10+c+11,) for c in range(nc)] for r in range(nr)]
print(lol)
# [['11', '12', '13', '14'],
#  ['21', '22', '23', '24'],
#  ['31', '32', '33', '34'],
#  ['41', '42', '43', '44'],
#  ['51', '52', '53', '54']]

# now, we build an AUGmented List Of Lists, prepending each row with
# its last element and appending the last one, prepending the first
# augmented row with the last row and appending the first to the last
aug_lol = [[lol[r%nr][c%nc] for c in range(-1,nc+1)] for r in range(-1,nr+1)]
print(aug_lol)
# [['54', '51', '52', '53', '54', '51'],
#  ['14', '11', '12', '13', '14', '11'],
#  ['24', '21', '22', '23', '24', '21'],
#  ['34', '31', '32', '33', '34', '31'],
#  ['44', '41', '42', '43', '44', '41'],
#  ['54', '51', '52', '53', '54', '51'],
#  ['14', '11', '12', '13', '14', '11']]

使用列表的aug_lol列表,您可以以最自然的方式查询元素11 (或其他什么)的邻居,

代码语言:javascript
复制
def neighborhood(alol, r, c):
    return [alol[nr][nc] for nc in range(c,c+3)
                         for nr in range(r,r+3)
                         if (nr!=(r+1) or nc!=(c+1))]

去数那些活着的邻居,

代码语言:javascript
复制
ln = sum(c=="X" for c in neighborhood(...))

要打印板,以下内容更有效

代码语言:javascript
复制
print('\n'.join(''.join(ch for ch in r) for r in board))
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29485769

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档