有没有办法减少if语句的数量?

2024-06-01 02:37:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尽我所能地消除这些情况。在这里,我有两个if语句,我想用一个或一个都不写同样的代码。你知道吗

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
    if team == -1:
        chosen_succ = player1.convert_board_state(chosen_succ)
    return chosen_succ

没有错误,它与额外的行代码工作正常。你知道吗


Tags: 代码boardconvertnewmoveif情况语句
2条回答

那些完全可读的if语句有什么问题?你知道吗

作为一个不完全严肃的选项,您可以用dict查找替换任何if:

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

为了使它更加简洁(即晦涩难懂),您还可以使用list。如果索引为False,则给出项0,如果索引为True,则给出项1:

# ...
[
    lambda: None,
    lambda: player1.convert_board_state(state)
][team==-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

就在那里!你知道吗

相关问题 更多 >