两种生成矩阵的方法:
先生成列表,再生成矩阵。
def ReadTxtName2(rootdir): # 按行读取txt,生成列表
lines = []
with open(rootdir, 'r') as file_to_read:
while True:
line = file_to_read.readline()
if not line:
break
line = line.strip() #去掉每行头尾空白
line = line.strip('\n') #去掉最后的换行符
if line:
s = line.split(' ') #每行元素间用空格做分割
a = []
for i in range(0, len(s)):
a.append(int(s[i]))
lines.append(a)
return lines
if __name__ == '__main__':
resultpath = r'新建文本文档.txt'
c = ReadTxtName2(resultpath)
print("c = ",c ,type(c))
# 生成矩阵
#方法1:
for i in range(0,len(c)):
c[i] = np.array(c[i])
d1 = np.array(c)
print("d1 = ",d1 ,type(d1))
#方法二:
d2 = np.matrix(c)
print("d2 = ",d2 ,type(d2))
运行结果:
运行结果