我有一個 txt 檔案,其中包含一些帶空格的數字,我想在 python 中將其作為三個 4*4 矩陣。每個矩陣也在文本檔案中用兩個符號劃分。txt檔案的格式是這樣的:
1 1
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
1 1
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
1 1
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
我的代碼現在是這樣的,但它沒有顯示我想要的輸出。
file = open('inputs.txt','r')
a=[]
for line in file.readlines():
a.append( [ int (x) for x in line.split('1 1') ] )
你能幫我解決這個問題嗎?
uj5u.com熱心網友回復:
一種選擇是使用groupby:
from itertools import groupby
matrices = []
with open('inputs.txt', 'r') as f:
for separator, lines in groupby(f, lambda line: line.strip() == '1 1'):
if not separator:
matrices.append([[int(x) for x in line.split()] for line in lines])
print(matrices)
# [[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]],
# [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]],
# [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]]
uj5u.com熱心網友回復:
一個很好的舊純 python 演算法(假設矩陣可以保存字串值,否則,根據需要進行轉換):
file = open("inputs.txt",'r')
matrices=[]
for line in file:
line=line.strip()
if line=="1 1":
if len(m)>0: matrices.append(m)
m=[]
else:
data=line.split(' ')
m.append(data)
if len(m)>0: matrices.append(m)
print(matrices)
# [[['0', '0', '0', '0'], ['0', '0', '0', '0'], ['0', '0', '0', '0'], ['0', '0', '0', '0']],
# [['0', '0', '0', '0'], ['0', '0', '0', '0'], ['0', '0', '0', '0'], ['0', '0', '0', '0']],
# [['0', '0', '0', '0'], ['0', '0', '0', '0'], ['0', '0', '0', '0'], ['0', '0', '0', '0']]]
uj5u.com熱心網友回復:
下面的代碼應該可以作業。
file = open('inputs.txt', 'r')
a = []
temp = []
for line in file.readlines():
if line == '1 1\n':
a.append(temp)
temp.clear()
else:
temp.append(line.strip().split(' '))
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/475074.html
上一篇:處理換行的shift enter,在TextEditorSwiftUI中輸入發送
下一篇:熊貓向前填充-相同的值
