如何避免if条件代码的重复代码块?

时间:2019-03-21 18:32:10

标签: python

基于特定的参数,我在python中有一些代码,如下所示。我想避免重复相同的代码块,我认为这不是明智的选择。

If arg is x:
Do_1(x)
Do_2
Do_3
...
else:
Do_1(arg)
Do_2
Do_3
...

替代品?

编辑:对模棱两可的问题表示抱歉,实际代码为:

对于范围为(0,21)的k:

iteration_directory = '%s/%s_round_%s' %(os.getcwd(), structure_name, k)

if not os.path.exists('%s/%s_round_%s' %(os.getcwd(), structure_name, k)):
    os.makedirs('%s/%s_round_%s' %(os.getcwd(), structure_name, k))

if start_model == 'null':

    if os.path.isfile( '%s/%s.1.silent' % (iteration_directory, structure_name))==False:
        Parallel(n_jobs=num_cores)(delayed(fragment_search_nomodel)(iteration_directory, rosetta_path, fasta, frag_file, structure_name, map_file, i) for i in residues)

    if os.path.isfile( '%s/scores1' % (iteration_directory))==False:
        fragment_score(rosetta_path, iteration_directory, structure_name)

    if os.path.isfile( '%s/assembled.1_0001.silent' % (iteration_directory))==False:
        Parallel(n_jobs=num_cores)(delayed(fragment_assembly)(rosetta_path, iteration_directory, structure_name, i) for i in residues)

    consensus_assignment(rosetta_path, iteration_directory, structure_name, k)

    start_model = '%s/%s_round_%s.pdb' % (os.getcwd(), structure_name, k) 


    print('Time for round #%s is: ' %k, datetime.now() - startTime)           

else:

    coverage = model_coverage(start_model,fasta)

    if coverage <= 70:

        if os.path.isfile( '%s/%s.1.silent' % (iteration_directory, structure_name))==False:
            Parallel(n_jobs=num_cores)(delayed(fragment_search)(iteration_directory, rosetta_path, fasta, frag_file, start_model, structure_name, map_file, i) for i in residues)

        if os.path.isfile( '%s/scores1' % (iteration_directory))==False:
            fragment_score(rosetta_path, iteration_directory, structure_name)

        if os.path.isfile( '%s/assembled.1_0001.silent' % (iteration_directory))==False:
            Parallel(n_jobs=num_cores)(delayed(fragment_assembly)(rosetta_path, iteration_directory, structure_name, i) for i in residues)

        consensus_assignment(rosetta_path, iteration_directory, structure_name, k)

        start_model = '%s/%s_round_%s.pdb' % (os.getcwd(), structure_name, k) 

        print('Time for round #%s is: ' %k, datetime.now() - startTime)

3 个答案:

答案 0 :(得分:2)

似乎

Do_1(arg)
Do_2()
Do_3()

无论您的if子句如何都会执行,因为无论arg值如何,您都将其传递给Do_1()方法。

答案 1 :(得分:1)

尽管两个if / else情况是等效的,但这似乎正是您所追求的:

if arg is x:
    Do_1(x)
else:
    Do_1(arg)
Do_2
Do_3

答案 2 :(得分:0)

或者您可以将Do_1的参数值设置为条件:

Do_1(x if arg is x else arg)
Do_2()
Do_3()