在Python中对多个变量进行基本模式匹配的惯用方式

时间:2018-07-25 20:31:25

标签: python pattern-matching idioms

我想实现此代码(用Crystal编写)的作用:

enum PieceKind
    Pawn, Rook, Bishop, Knight, King, Queen
end

def piece_kind_at_init(x, y)
    case y
    when 2, 7 then PieceKind::Pawn
    when 1, 8
        case x
        when 1, 8 then PieceKind::Rook
        when 2, 7 then PieceKind::Bishop
        when 3, 6 then PieceKind::Knight
        when 4 then PieceKind::King
        when 5 then PieceKind::Queen
        end
    end
end

这是我在Python中能够想到的“最棒的”版本:

class PieceKind(Enum):
    Pawn = auto()
    Rook = auto()
    Bishop = auto()
    Knight = auto()
    King = auto()
    Queen = auto()

def piece_kind_at_init(x, y):
    if y in [2, 7]:     
        return PieceKind.Pawn
    elif y in [1, 8]:
        if x in [1, 8]:     
            return PieceKind.Rook
        elif x in [2, 7]:   
            return PieceKind.Bishop
        elif x in [3, 6]:   
            return PieceKind.Knight
        elif x == 4:        
            return PieceKind.King
        elif x == 5:        
            return PieceKind.Queen

很好,但是使用适当的模式匹配的版本肯定可读性较差。编写代码最惯用的方式是什么?

1 个答案:

答案 0 :(得分:0)

摆脱冗长的elif链的一种方法是创建翻译表。

outer_row_pieces = [PieceKind.Rook,
                    PieceKind.Knight,
                    PieceKind.Bishop,
                    PieceKind.King,
                    PieceKind.Queen,
                    PieceKind.Bishop,
                    Piecekind.Knight,
                    PieceKind.Rook]

def piece_kind_at_init(x, y):
    if y == 2 or y == 7:
        return PieceKind.Pawn
    if y == 1 or y == 8:
        return outer_row_pieces[x]
    return None