我在列表中有三个列表。我想更改特定列表的特定元素。让我们说第二个列表,第一个元素。我试过这样的话:
以下是整件事,我只是学习如何编程,所以不要评判我:)
class Board:
#creates visible playing board
global rows
rows = []
def create_row(self):
row1 = []
while len(row1) <= 4:
if len(row1) <= 3:
row1.append("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()
答案 0 :(得分:2)
跟踪这个 - 假设我们在提示时输入'3',所以height = 2;那么
for i in rows[2]:
i的第一个值是'x'
'x'[2] = 'a'
这会给你错误 - 你不能改变字符串中的字符,因为字符串是不可变的(而你必须构造一个新的字符串并替换旧的字符串)。
请尝试以下方法:
def getInt(msg):
return int(raw_input(msg))
row = getInt('Which row? ')
col = getInt('Which col? ')
rows[row-1][col] = 'a'
请尝试以下方法:
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()