简体   繁体   English

为战舰创建并初始化5x5网格

[英]Create and initialize 5x5 grid for Battleships

So I just completed a section of CodeAcademy Battleship problem, and have submitted a correct answer but am having trouble understanding why it is correct. 所以我刚刚完成了CodeAcademy Battleship问题的一部分,并提交了正确的答案,但我很难理解为什么它是正确的。

The idea is to build a 5x5 grid as a board, filled with "O's". 我们的想法是建立一个5x5网格作为板,填充“O”。 The correct code I used was: 我使用的正确代码是:

board = []
board_size=5

for i in range(board_size):

    board.append(["O"] *5)

However I'm confused as to why this didn't create 25 "O's" in one single row as I never specified to iterate to a separate row. 但是我很困惑为什么这不会在一行中创建25个“O”,因为我从未指定迭代到单独的行。 I tried 我试过了

for i in range(board_size):

    board[i].append(["O"] *5)

but this gave me the error: IndexError: list index out of range . 但这给了我错误: IndexError: list index out of range Can anyone explain why the first one is correct and not the second one? 任何人都可以解释为什么第一个是正确的而不是第二个?

["O"]*5

This creates a list of size 5, filled with "O": ["O", "O", "O", "O", "O"] 这将创建一个大小为5的列表,其中填充“O”: ["O", "O", "O", "O", "O"]

board.append(["O"] *5)

This appends (adds to the end of the list) the above list to board[]. 这将上面的列表添加(添加到列表的末尾)到board []。 Doing this 5 times in a loop creates a list filled with 5 of the above lists. 在循环中执行此操作5次会创建一个列表,其中包含上述5个列表。

[["O", "O", "O", "O", "O"],
["O", "O", "O", "O", "O"],
["O", "O", "O", "O", "O"],
["O", "O", "O", "O", "O"],
["O", "O", "O", "O", "O"]]

Your code did not work, because lists are not initialized with a size in python, it just starts as an empty container [] . 你的代码不起作用,因为列表没有用python中的大小初始化,它只是作为一个空容器[] To make yours work, you could have done: 为了让你的工作,你可以做到:

board = [[],[],[],[],[]]

and in your loop: 在你的循环中:

board[i] = ["O"]*5

Python lists start out empty: Python列表从空开始:

board = [] # empty list

Unlike some programming languages, you do not specify or initialise the bounds of the array, so if you try to access by index: 与某些编程语言不同,您不指定或初始化数组的边界,因此如果您尝试通过索引访问:

board[0]

you will get an IndexError ; 你会得到一个IndexError ; there is not yet any index 0 . 还没有任何索引0

In the first version, on each trip through the for loop, you append (add to the end of the list) a new list containing five "O" s. 在第一个版本中,在每次通过for循环的行程中,您append (添加到列表的末尾)一个包含五个"O"新列表 If you want the board list to contain 25 "O" s, you should use extend instead: 如果您希望board列表包含25 "O" ,则应使用extend代替:

for i in range(board_size):
    board.extend(["O"] *5)

Code should look like this. 代码应如下所示。 board = [] for i in range(0, 5): board.append(["O"]*5) print(board)

I think the problem is simple: when you run your code, your array is empty! 我认为问题很简单:当你运行代码时,你的数组是空的!

You could issue a 你可以发一个

board = [[], [], [], [], []]

to initialize it as a nested, five places array. 将其初始化为嵌套的五位数组。

You could also use a dict to simulate a indefinitely nested array: 您还可以使用dict来模拟无限嵌套的数组:

board=defaultdict(lambda:defaultdict(lambda:[]))

This is because each time you run board.append(["O"] *5) you create a new list (because of the square brackets used inside the append statement). 这是因为每次运行board.append(["O"] *5)都会创建一个新列表(因为append语句中使用了方括号)。

If you would have used board.append("O" *5) instead the you would get a single list with five elements like: 如果您使用board.append("O" *5)代替,您将得到一个包含五个元素的列表:

['OOOOO', 'OOOOO', 'OOOOO', 'OOOOO', 'OOOOO'] ['OOOOO','OOOOO','OOOOO','OOOOO','OOOOO']

The *5 multiplies the string. * 5乘以字符串。 if you just run from an interactive prompt 'O' * 5 you get: 如果你只是从交互式提示'O' * 5你会得到:

'OOOOO' 'OOOOO'

However, if you run ['O'] * 5 it multiplies the text within the list and you get a list with five elements. 但是,如果你运行['O'] * 5它会将列表中的文本相乘,你会得到一个包含五个元素的列表。

['O', 'O', 'O', 'O', 'O'] ['O','O','O','O','O']

You appended five lists, each having 5 elements. 您附加了五个列表,每个列表包含5个元素。

board = []
board_size=5

for i in range(board_size):

    board.append(["O"] *5)

In this code board starts as an empty list. 在此代码board中以空列表开头。 ["O"] * 5 will create a list that is equal to ["O", "O", "O", "O", "O"] . ["O"] * 5将创建一个等于["O", "O", "O", "O", "O"] It will then be appended to the list board . 然后它将附加到列表board This will happen 5 times in this example since board_size == 5 . 由于board_size == 5在此示例中将发生这种情况5次。

for i in range(board_size):

    board[i].append(["O"] *5)

This wouldn't work unless the item at index i was a list since append() is a method of the list class. 除非索引i的项是列表,否则这将无效,因为append()list类的方法。 If you wanted to insert something at i you would use the list method insert() 如果你想在i处插入一些东西,你会使用list方法insert()

First step in codeacademy codeacademy的第一步

board = []
for i in range(5):
    board.append(["O"]*5)

print board

Second step in codeacademy codeacademy的第二步

board = []

def print_board(board):
    for x in range(5):
        board= (["O"] * 5)
        print board
    return board

print_board(board)

third step in codeacademy codeacademy的第三步

board = []

def print_board(board):
    for x in range(5):
        board= (["O"] * 5)
        print " ".join(board)
    return board

print_board(board)

4th Step 第四步

from random import randint 

board = []

for x in range(0, 5):
    board.append(["O"] * 5)

def print_board(board):
    for row in board:
        board = " ".join(row)
        return  board

def random_row(board):
    return randint(0, len(board) - 1)

def random_col(board):
    return randint(0, len(board) - 1)

print print_board(board)
print random_row(board)
print random_col(board)

5th step of buttleship on codeacademy 在codeacademy上的第五步buttleship

from random import randint

board = []

for x in range(0,5):
    board.append(["O"] * 5)

def print_board(board):
    for row in board:
        print " ".join(row)

def random_row(board):
    return randint(0, len(board) - 1)

def random_col(board):
    return randint(0, len(board[0]) - 1)

ship_row = random_row(board)
ship_col = random_col(board)


guess_row = int(raw_input("Guess Row: "))
guess_col = int(raw_input("Guess Col: "))

Final Step Lets .. Play game BettleShip CodeAcademy 最后一步让我们玩游戏BettleShip CodeAcademy

from random import randint

board = [] for x in range(5): board.append(["O"] * 5) board = [] for x in range(5):board.append([“O”] * 5)

def print_board(board): for row in board: print " ".join(row) def print_board(board):for board in board:print“”。join(row)

print "Let's play Battleship!" 打印“让我们玩战舰!” print_board(board) print_board(板)

def random_row(board): return randint(0, len(board) - 1) def random_row(board):return randint(0,len(board) - 1)

def random_col(board): return randint(0, len(board[0]) - 1) def random_col(board):return randint(0,len(board [0]) - 1)

ship_row = random_row(board) ship_col = random_col(board) print ship_row print ship_col ship_row = random_row(board)ship_col = random_col(board)print ship_row print ship_col

turns=0 win = 0 for turn in range(4): if turn <= 5: guess_row = int(raw_input("Guess Row:")) guess_col = int(raw_input("Guess Col:")) turn = 0 win = 0 for turn in range(4):if turn <= 5:guess_row = int(raw_input(“Guess Row:”))guess_col = int(raw_input(“Guess Col:”))

    if guess_row == ship_row and guess_col == ship_col:
        print "Congratulations! You sunk my battleship!"
        win +=1
        if win == 2:
            break
    else:
        turns +=1
        if (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4):
            print "Oops, that's not even in the ocean."
        elif(board[guess_row][guess_col] == "X"):
            print "You guessed that one already."
        else:
            print "You missed my battleship!"
            board[guess_row][guess_col] = "X"
            print (turn + 1)
        print_board(board)
elif turns == 3:
    print "Game Over"
else:
    print "Max Turn try is over Try Again"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM