减少冗余编码的Python 3

时间:2019-03-15 17:58:06

标签: python python-3.x

我在一个类中有这个功能

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]

它基本上是在输入文件("Ks")中搜索模式(inFile),以将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

2 个答案:

答案 0 :(得分:5)

使用元组拆包:

self.Ks, self.thetaS, self.thetaR, self.alpha, self.lamb, self.n = nextLine.split()

答案 1 :(得分:2)

另一种可能性是使用标准CSV package

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))