[英]Reduce redudant coding Python 3
我在一個班級里有這個功能
def readInput(self, inFile):
with open(inFile, "r") as file:
for line in file:
if (line.split()[0] == "Ks"):
nextLine = next(file)
self.Ks = nextLine.split()[0]
self.thetaS = nextLine.split()[1]
self.thetaR = nextLine.split()[2]
self.alpha = nextLine.split()[3]
self.lamb = nextLine.split()[4]
self.n = nextLine.split()[5]
它基本上是在輸入文件( inFile
)中搜索模式( "Ks"
),以將inFile
下一行的變量值存儲在實例變量中。
代碼中有很多重復,我認為有可能以一種聰明(而且更短)的方式編寫代碼。
有任何想法嗎?
輸入文件如下所示:
### Soil hydraulic properties. Units: m, d
Ks ThetaS ThetaR alpha lambda n
0.128 0.01 0.42 0.84 -1.497 1.441
使用元組拆包:
self.Ks, self.thetaS, self.thetaR, self.alpha, self.lamb, self.n = nextLine.split()
另一種可能性是使用標准CSV包 。
import csv
with open('testdata.csv', newline='') as file:
csvreader = csv.reader(file, delimiter=' ', skipinitialspace=True)
next(csvreader) # omit the comment at start of file
header = next(csvreader)
for row in csvreader:
print(', '.join(row))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.