Change a specific element of a list in python?
I have three lists inside a list. I want to change a specific element of a specific list. So lets say the second list, first element. I tried it like this:
Here is the whole thing, I am just learning how to program so don't judge me :)
class Board:
#creates visible playing board
global rows
rows = []
def create_row(self):
row1 = []
while len(row1) <= 4:
if len(row1) <= 3:
row1.a开发者_Python百科ppend("x")
else:
row1.append("\n")
rows.append(row1)
def input(self):
print "Enter a colum num"
height = int(raw_input(">"))
height = height - 1
print "Enter a row num"
width = raw_input(">")
print rows.__class__
# for i in rows[height]:
# i[height] = 'a'
def display(self):
for i in rows:
for m in i:
print m,
row1 = Board()
row1.create_row()
row2 = Board()
row2.create_row()
row3 = Board()
row3.create_row()
row4 = Board()
row4.create_row()
row4.display()
row4.input()
row4.display()
Trace this through - assume we enter '3' when prompted, so height = 2; then
for i in rows[2]:
the first value of i is 'x'
'x'[2] = 'a'
and this gives you your error - you cannot change a character in the string because strings are immutable (instead you have to construct a new string and replace the old one).
Try the following instead:
def getInt(msg):
return int(raw_input(msg))
row = getInt('Which row? ')
col = getInt('Which col? ')
rows[row-1][col] = 'a'
Try the following instead:
def getInt(msg, lo=None, hi=None):
while True:
try:
val = int(raw_input(msg))
if lo is None or lo <= val:
if hi is None or val <= hi:
return val
except ValueError:
pass
class GameBoard(object):
def __init__(self, width=4, height=4):
self.width = width
self.height = height
self.rows = [['x']*width for _ in xrange(height)]
def getMove(self):
row = getInt('Please enter row (1-{0}): '.format(self.height), 1, self.height)
col = getInt('Please enter column (1-{0}): '.format(self.width), 1, self.width)
return row,col
def move(self, row, col, newch='a'):
if 1 <= row <= self.height and 1 <= col <= self.width:
self.rows[row-1][col-1] = newch
def __str__(self):
return '\n'.join(' '.join(row) for row in self.rows)
def main():
bd = GameBoard()
row,col = bd.getMove()
bd.move(row,col)
print bd
if __name__=="__main__":
main()
精彩评论