有什么办法可以减少if语句的数量?

时间:2019-05-22 09:47:07

标签: python if-statement

如果可能的话,我会尽量消除这些情况。在这里,我确实有两个if语句,并且我想只用一个或一个都不编写相同的代码。

<div class="container">
 <div class="content">
  <p>Hello World</p>
  <p>Hello World</p>
 </div>
</div>

<div class="container">
 <div class="content no_p_margin">
  <p>Hello World</p>
  <p>Hello World</p>
 </div>
</div>

没有错误,可以使用额外的行代码。

2 个答案:

答案 0 :(得分:1)

那些完全可读的if语句怎么了?

作为一种不太重要的选择,您可以将所有if替换为dict查找:

# ...
options = {
    False: lambda: None
    True: lambda: player1.convert_board_state(state)
}
options[team==-1]()
# ...

要使其更加简洁(即晦涩),您还可以使用列表。索引为False时,项0;索引为True时,项1:

# ...
[
    lambda: None,
    lambda: player1.convert_board_state(state)
][team==-1]()
# ...

答案 1 :(得分:1)

您可以将team == -1时的逻辑与team != -1分开:

def ai_player(self, state, team = 1): 
    new_shape_x = np.asarray(state[1]).shape
    player1 = Minimax(n = new_shape_x, default_team = team)

    if team == -1:
        state = player1.convert_board_state(state)
        best_move = player1.decision_maker(state)
        chosen_succ, utility = best_move
        chosen_succ = player1.convert_board_state(chosen_succ)
    else:
        best_move = player1.decision_maker(state)
        chosen_succ, utility = best_move

    return chosen_succ

虽然会有重复的代码。

在这种情况下,您还可以将重复的两行变成一条,从而清楚地表明代码的这一部分就是重复的部分:

def ai_player(self, state, team = 1): 
    new_shape_x = np.asarray(state[1]).shape
    player1 = Minimax(n = new_shape_x, default_team = team)

    if team == -1:
        state = player1.convert_board_state(state)
        chosen_succ, utility = player1.decision_maker(state)
        chosen_succ = player1.convert_board_state(chosen_succ)
    else:
        chosen_succ, utility = player1.decision_maker(state)

    return chosen_succ

现在变量best_move消失了。如果您仍然想说自己正在选择最好的棋步,可以将decision_maker方法重命名为choose_best_move

def ai_player(self, state, team = 1): 
    new_shape_x = np.asarray(state[1]).shape
    player1 = Minimax(n = new_shape_x, default_team = team)

    if team == -1:
        state = player1.convert_board_state(state)
        chosen_succ, utility = player1.choose_best_move(state)
        chosen_succ = player1.convert_board_state(chosen_succ)
    else:
        chosen_succ, utility = player1.choose_best_move(state)

    return chosen_succ

就在那里!