Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/347.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/amazon-s3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
编写python程序混合使用split和join的更好技巧_Python_Python 2.7 - Fatal编程技术网

编写python程序混合使用split和join的更好技巧

编写python程序混合使用split和join的更好技巧,python,python-2.7,Python,Python 2.7,我编写了以下代码: with open('inputfile.txt') as f: #sending second line to variable port1 port1 = (f.readlines()[1]) # Make proper space port1 = " ".join(port1.split()) print port1 # fetch eth0 to port1 variable port1 = p

我编写了以下代码:

 with open('inputfile.txt') as f:
     #sending second line to variable port1
     port1 = (f.readlines()[1])
     # Make proper space 
     port1 = " ".join(port1.split())
     print port1
     # fetch eth0 to port1 variable
     port1 = port1.split(" ")[1]
     print port1
inputfile.txt
包含:

  server port1 port2
  server1  eth1    eth2
  server2  eth7    eth8
以上代码运行良好。我得到了预期的结果


但代码似乎不是标准的。我多次使用了
port1
。有没有更好的方法来编写此代码?

我不知道是否更好,但另一种方法可能是生成每行代码,如果您知道有多少行:

def get_conf(fn='inputfile.txt'):
    with open(fn) as f:
        for line in f.readlines():
            yield line.split()

c = get_conf()
s, p1, p2 = next(c)
s1, a1, b1 = next(c)
s2, a2, b2 = next(c)

我不知道这是否更好,但另一种方法可能是产生每一行,如果你知道有多少行:

def get_conf(fn='inputfile.txt'):
    with open(fn) as f:
        for line in f.readlines():
            yield line.split()

c = get_conf()
s, p1, p2 = next(c)
s1, a1, b1 = next(c)
s2, a2, b2 = next(c)

您可以避免拆分并重新加入“游戏”,如下所示:

with open('inputfile.txt') as f:
     #sending second line to variable port1
     port1 = f.readlines()[1]
     # prepare for further processing:
     port1 = port1.split()
     # Print with proper space 
     print " ".join(port1)
     # print eth1 (your input data has no eth0)
     print port1[1]

您可以避免拆分并重新加入“游戏”,如下所示:

with open('inputfile.txt') as f:
     #sending second line to variable port1
     port1 = f.readlines()[1]
     # prepare for further processing:
     port1 = port1.split()
     # Print with proper space 
     print " ".join(port1)
     # print eth1 (your input data has no eth0)
     print port1[1]