且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我可以在Python中使用带条件的if-else语句使用嵌套的for循环吗?

更新时间:2023-11-14 19:48:22

首先,我建议将此检查外包给专用功能.

First, I would recommend outsourcing this check to a dedicated function.

第二,可以将dict与期望的最大值一起使用,并对 all()进行理解以更简洁地执行检查.

Second, you can use a dict with your expected max values, and use a comprehension with all() to perform the check more concisely.

max_counts = {
    'bking': 1,
    'bqueen': 1,
    '***': 2,
    'bknight': 2,
    'bbishop': 2,
    'bpawn': 8,
    'wking': 1,
    'wqueen': 1,
    'wrook': 2,
    'wknight': 2,
    'wbishop': 2,
    'wpawn': 8
}

def board_is_valid(count, board):
    return len(board) <= 32 and all(
               count[piece] <= ct 
               for (piece, ct) in max_counts.items()
           )

如果您想稍微减少 max_counts 的详细程度,则可以尝试创建一个包含 king queen 基本计数的虚拟字典, rook 等,并使 max_counts 成为添加该列表的两个副本的结果,每个副本的前缀为'b'另一个是'w'.但是,如果这是整组作品,我认为没有必要.

If you want to be slightly less verbose with max_counts, you could try creating a dummy dict with the basic counts for king, queen, rook, etc., and make max_counts the result of adding two copies of that list, one with 'b' prefixed to each key and the other with 'w'. But I don't think thats necessary if this is the entire set of pieces.

还请注意,这可能不是棋盘验证的万无一失的方法.典当可能会升级为国王以外的任何其他类型的棋子,因此从技术上来说,拥有一个以上的女王或两个以上的白嘴鸦是可能的.

Also consider that this may not be a foolproof method of validation for your chessboard. Pawns may promote into any other type of piece besides king, so having more than one queen or more than two rooks is technically possible.