0
我需要編寫一段代碼來讀取一個.txt文件,它是一個如下所示的矩陣,並將其轉換爲一個新的整數列表矩陣。但是,我想跳過此.txt文件的第一行,而無需手動刪除文件。我不知道如何去做。 我寫了一些代碼。它能夠顯示矩陣,但我無法擺脫的第一線:前一陣如何在python中跳過文件的第一行
def display_matrix(a_matrix):
for row in a_matrix:
print(row)
return a_matrix
def numerical_form_of(a_list):
return [int(a_list[i]) for i in range(len(a_list))]
def get_scoring_matrix():
scoring_file = open("Scoring Matrix")
row_num = 0
while row_num <= NUMBER_OF_FRAGMENTS:
content_of_line = scoring_file.readline()
content_list = content_of_line.split(' ')
numerical_form = numerical_form_of(content_list[1:])
scoring_matrix = []
scoring_matrix.append(numerical_form)
row_num += 1
#print(scoring_matrix)
display_matrix(scoring_matrix)
# (Complement): row_num = NUMBER_OF_FRAGMENTS
return scoring_matrix
get_scoring_matrix()
Scoring Matrix is a .txt file:
1 2 3 4 5 6 7
1 0 1 1 1 1 1 1
2 0 0 1 1 1 1 1
3 0 0 0 1 1 1 1
4 0 0 0 0 1 1 1
5 0 0 0 0 0 1 1
6 0 0 0 0 0 0 1
7 0 0 0 0 0 0 0
The result of my code:
[1, 2, 3, 4, 5, 6, 7]
[0, 1, 1, 1, 1, 1, 1]
[0, 0, 1, 1, 1, 1, 1]
[0, 0, 0, 1, 1, 1, 1]
[0, 0, 0, 0, 1, 1, 1]
[0, 0, 0, 0, 0, 1, 1]
[0, 0, 0, 0, 0, 0, 1]
[0, 0, 0, 0, 0, 0, 0]
哇,非常感謝!改變while循環的工作原理,但爲什麼最後一行顯示一個空列表:[0,1,1,1,1,1,1] [0,0,1,1,1,1,1] [0 ,0,0,1,1,1,1] [0,0,0,0,1,1,1] [0,0,0,0,0,1,1] [0,0 ,0,0,0,0,1] [0,0,0,0,0,0,0] [] –
@ZichenMa可能是因爲您的文件末尾有額外的回車,可能與最後一行有一些空格。 – gt6989b
非常感謝! –