如何避免在for + if链中复制代码?

时间:2017-10-10 15:14:05

标签: python python-2.7

如何避免将代码拆分为两个独立的部分? 我试图只调用一次“DoSomething _...”函数,但在两种情况下均可使用。 我可能会为此添加更多“for(s)”,问题是我必须处理单独的代码部分。

    for first in FIRST_LIST:
      for second in SECOND_LIST:
          for third in THIRD_LIST:
              if third!='Some specific thing':
                  for fourth in FOURTH_LIST:
                      DoSomething_K_x_fourth_Times(first,second,third,fourth)
              else:
                  forth=0
                  DoSomething_K_Times(first,second,third,fourth)

2 个答案:

答案 0 :(得分:2)

根据条件创建包含单个项[0]FOURTH_LIST的列表,并迭代列表:

for first in FIRST_LIST:
    for second in SECOND_LIST:
        for third in THIRD_LIST:
            if third == 'Some specific thing':
                a_list = [0]
            else:
                a_list = FOURTH_LIST
            for fourth in a_list:
                DoSomething_K_x_fourth_Times(first, second, third, fourth)

<强>更新

根据条件将不同的函数分配给变量(func在下面的代码中),然后调用函数。

for first in FIRST_LIST:
    for second in SECOND_LIST:
        for third in THIRD_LIST:
            if third == 'Some specific thing':
                a_list = [0]
                func = DoSomething_K_x_fourth_Times
            else:
                a_list = FOURTH_LIST
                func = DoSomething_K_Times

            for fourth in a_list:
                func(first, second, third, fourth)

答案 1 :(得分:0)

  def DoSomething_K_Times(first,second,third,splitpoint):
      for x in splitpoint:
          ...

  for first in FIRST_LIST:
      for second in SECOND_LIST:
          for third in THIRD_LIST:
              if third != 'Some specific thing':
                  DoSomething_K_Times(first,second,third,FOURTH_LIST)
              else:
                  DoSomething_K_Times(first,second,third,[0])