2016-09-01 26 views
0

我正在嘗試編寫一個「。」列表。在每個索引上的次數應該是遊戲板中應該有的行和列。這是我正在使用的代碼,但是我得到的錯誤是告訴我,我不能用'str'類型的非整型來乘序列。我正在使用python 3.5.2。如何在python中創建x個字符的列表?

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) 
+0

您將'rows'和'columns'轉換爲整數,但對新值無效 – Li357

回答

4

你非常接近。

你只需要將新的int值賦給變量。 int()不會更改該變量,只返回一個新值。

因此,爲了得到正確的行值使用:

rows = int(rows) 

與同爲列

順便說一句,你也應該看看自己是如何產生你的董事會。你可能想要一個2x2電路板的[[。。,「。」],[「。」,「。」]]。我建議你看看列表解析

0

你的代碼中有另一個問題,其他答案沒有解決。

>>> ['.'] * 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', '.', '.', '.', '.'], ['.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.']] 
相關問題