可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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.
The idea is to build a 5x5 grid as a board, filled with "O's". 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. 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
. Can anyone explain why the first one is correct and not the second one?
回答1:
["O"]*5
This creates a list of size 5, filled with "O": ["O", "O", "O", "O", "O"]
board.append(["O"] *5)
This appends (adds to the end of the list) the above list to board[]. Doing this 5 times in a loop creates a list filled with 5 of the above lists.
[["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 []
. To make yours work, you could have done:
board = [[],[],[],[],[]]
and in your loop:
board[i] = ["O"]*5
回答2:
Python lists start out empty:
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
; there is not yet any index 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. If you want the board
list to contain 25 "O"
s, you should use extend
instead:
for i in range(board_size):
board.extend(["O"] *5)
回答3:
Code should look like this.
board = []
for i in range(0, 5):
board.append(["O"]*5)
print(board)
回答4:
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:
board=defaultdict(lambda:defaultdict(lambda:[]))
回答5:
board = []
board_size=5
for i in range(board_size):
board.append(["O"] *5)
In this code board
starts as an empty list. ["O"] * 5
will create a list that is equal to ["O", "O", "O", "O", "O"]
. It will then be appended to the list board
. This will happen 5 times in this example since board_size == 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. If you wanted to insert something at i
you would use the list method insert()
回答6:
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).
If you would have used board.append("O" *5)
instead the you would get a single list with five elements like:
['OOOOO', 'OOOOO', 'OOOOO', 'OOOOO', 'OOOOO']
The *5 multiplies the string. if you just run from an interactive prompt 'O' * 5
you get:
'OOOOO'
However, if you run ['O'] * 5
it multiplies the text within the list and you get a list with five elements.
['O', 'O', 'O', 'O', 'O']
You appended five lists, each having 5 elements.
回答7:
First step in codeacademy
board = []
for i in range(5):
board.append(["O"]*5)
print board
Second step in 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
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
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
from random import randint
board = []
for x in range(5):
board.append(["O"] * 5)
def print_board(board):
for row in board:
print " ".join(row)
print "Let's play Battleship!"
print_board(board)
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)
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:"))
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"