如何以简单的方式编写代码python2.7

时间:2018-10-16 08:56:09

标签: python-2.7

这是我的代码,并且运行良好。还有其他方法可以在一个函数本身中编写这样的代码(以使代码更简单),以便服务器使用list_server,server1使用list_server1,server2使用list_server2和server3使用list_server3

server = ['10.10.1.21','10.10.1.22','10.10.1.23']
server1 = ['10.10.1.51','10.10.1.52','10.10.1.53']
server2 = ['10.10.1.31','10.10.1.32','10.10.1.33']
server3 = ['10.10.1.41','10.10.1.42','10.10.1.43']

list_server = ['java','java1','java2']
list_server1 = ['process','process1']
list_server2 = ['check','check']
list_server3 = ['list','list1']

def func1():
    for hostname in server:
        for i in list_server:
            <my statements>
        else:
             <my statments>

def func2():
    for hostname1 in server1:
        for j in list_server1:
            <my statements>
        else:
             <my statments>

def func3():
    for hostname2 in server2:
        for k in list_server2:
            <my statements>
        else:
             <my statments>

def func4():
    for hostname3 in server3:
        for l in list_server3:
            <my statements>
        else:
             <my statments>

def main():
    func1()
    func2()
    func3()
    func4()

if __name__ == "__main__":
    main()

1 个答案:

答案 0 :(得分:1)

如果您的<my statements>对每个函数都相同,请使用参数截取代码:

def myFunc(s, ls):
    for hostname in s:
        for i in ls:
            <my statements>
        else:
             <my statments>

然后,使用不同的参数调用它:

def main():
    myFunc(server, list_server)
    myFunc(server1, list_server2)
    myFunc(server2, list_server3)
    myFunc(server3, list_server4)