python - 更改 python 中列表的特定元素?

标签 python arrays

我在一个列表中有三个列表。我想更改特定列表的特定元素。那么我们可以说第二个列表,第一个元素。我尝试过这样的:

这就是全部内容,我只是在学习如何编程,所以不要评判我:)

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()

最佳答案

追踪这一点 - 假设我们在提示时输入“3”,因此高度 = 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()

关于python - 更改 python 中列表的特定元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5690822/

相关文章:

Python "if X == Y and Z"语法

Python HackerRank Bonetrousle 代码超时

python - View app.views.MyWizard 未返回 HttpResponse 对象

python - 如何返回具有相应角度的数组中的最大值

c# - C# 中的数组搜索

arrays - Extendscript 调试数组

python - 在 Ubuntu 上,如何安装更新版本的 python 并保留旧版本的 python?

python - 如何导出和保存链接的 Jupyter 笔记本?

java - 使用不同的表达式分割字符串

c++ - 将数组传递给 boolean 函数