如何在python中创建x个字符的列表?

2024-10-02 02:34:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图写一个列表,在每个索引是一个“.”的次数应该有很多行和列在我的游戏板。这是我正在使用的代码,但我得到的错误是告诉我,我不能乘以一个非int的'str'类型的序列。我使用的是python3.5.2。你知道吗

def mkBoard(rows,columns):
    board = ["."] * rows * columns
    return board

#Take user input for number of rows and columns for the board and converts them into integers
rows = input('Enter the number of rows:')
int(rows)
columns = input('Enter the number of columns:')
int(columns)

#Create the board
board = mkBoard(rows,columns)

Tags: columnsandoftheboardnumber列表for
2条回答

代码中还有另一个问题,而另一个答案没有解决。你知道吗

>>> ['.'] * 5 * 5
['.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.']

你的电路板初始化创建了一个平面列表,这大概不是你想要的。通常情况下,您会为此使用一个列表列表。但是,使用重载乘法是创建列表列表的一种非常糟糕的方法:

>>> [['.'] * 5] * 5
[['.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.']]

因为现在:

>>> board = _
>>> board[0][0] = 'hi'
>>> board
[['hi', '.', '.', '.', '.'], ['hi', '.', '.', '.', '.'], ['hi', '.', '.', '.', '.'], ['hi', '.', '.', '.', '.'], ['hi', '.', '.', '.', '.']]

每一行都是同一列表的副本。您应该更喜欢列表理解:

>>> board = [['.' for row in range(5)] for col in range(5)]
>>> board
[['.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.']]
>>> board[0][0] = 'hi'
>>> board
[['hi', '.', '.', '.', '.'], ['.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.']]

你很接近。你知道吗

您只需要将新的int值赋给变量。int()不更改变量,只返回一个新值。你知道吗

因此,要获得正确的行值,请使用:

rows = int(rows)

列也一样

作为旁白,你还应该看看你是如何生成你的董事会。对于2x2板,您可能需要类似[[“.”、“.”、[“.”、“]”这样的内容。我建议你看一下清单

相关问题 更多 >

    热门问题