我現在正在學習 python 的入門課程,但在完成這項任務時遇到了一些麻煩。
我有兩個格式的字串:
a b c d e
f g h i l
我需要從 .txt 檔案中獲取這些字串,將它們作為矩陣轉換為垂直格式,如下所示:
a f
b g
c h
d i
e l
并放入另一個 .txt 檔案,而不使用 numpy 和 pandas 庫。問題是從這樣的矩陣:
1 2 3 4 5
6 7 8 9 10
每個數字不必是整數,我需要得到這個矩陣:
1 6
2 7
3 8
4 9
5 10
現在我只能用小數得到:
1.0 6.0
2.0 7.0
3.0 8.0
4.0 9.0
5.0 10.0
因此,從我的 POW 中,我需要以某種方式從最終結果中洗掉 .0,但我不知道如何從字串中洗掉小數,包括浮點數。
這是我的代碼:
with open('input.txt') as f:
Matrix = [list(map(float, row.split())) for row in f.readlines()]
TrMatrix=[[Matrix[j][i] for j in range(len(Matrix))] for i in range(len(Matrix[0]))]
file=open('output.txt','w')
for i in range(len(TrMatrix)):
print(*TrMatrix[i],file=file)
uj5u.com熱心網友回復:
據我了解您的問題,這是解決方案
with open('input.txt') as f:
cols = []
for row in f.readlines():
col = [int(float(i)) for i in row.split()]
cols.append(col)
new_rows = []
for i in range(len(cols[0])):
new_rows.append(' '.join([str(col[i]) for col in cols]))
Tr_matrix = '\n'.join(new_rows)
with open('output.txt','w') as file:
file.write(Tr_matrix)
print(Tr_matrix)
輸入:
1 2 3 4.6 5.4
6 7 8 9 10
輸出:
1 6
2 7
3 8
4 9
5 10
uj5u.com熱心網友回復:
將浮點數更改為整數。float 包含小數。int 沒有。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/535258.html
