Skip to main content
 首页 » 编程设计

Python:在继续之前完成对列表的迭代检查

2025年05月04日13mayingbao

所以我有这个来获取用户的输入(刚刚学习 Python,使用 2.7 因为有人告诉我):

def get_move_order(): 
    global move_order 
    move_order=[q for q in raw_input("Enter your move order: ")] 
    print "Checking the validity of your move..." 
    check_correct_moves_only() 

我有这个来确保它只有移动列表中的字母:

def check_correct_moves_only(): 
    moves = ['A','D','S','C','H'] 
    if all(move_order) in moves: 
        return start() 
    else: 
        print "That's not a proper move!" 
        return get_move_order() 

问题是,出于某种原因,这并不能真正起作用。我最初是这样的:

def check_correct_moves_only(): 
    moves = ['A','D','S','C','H'] 
        for q in move_order: 
            if q not in moves: 
                print "That's not a proper move!" 
                return get_move_order() 
            else: 
                return start() 

但这将返回诸如 AAAAAAR 之类的正确输入六次(在这种情况下,通过打印“Player 1 ready!”六次和“这不是正确的移动!”一次。我希望它检查所有七个(考虑回合制游戏,但每个玩家一次给出七个命令)在继续我在 start() 中的其他检查之前针对此错误,但我无法使所有功能正常工作/也许我正在使用错了吗?我也尝试过使用 any,但没有用。

请您参考如下方法:

我会向您提出以下建议:

def get_move_order():  # Asks for a move order until a valid list of moves was entered 
    while True: 
        move_order = [q for q in raw_input("Enter your move order: ")] 
 
        print "Checking the validity of your move..." 
        if check_correct_moves_only(move_order): 
            break  # breaks out of the while loop 
        else: 
            print "That's not a proper move!" 
    # valid move has been entered. Start the game. 
    start(move_order) 
 
def check_correct_moves_only(move_order): 
    moves = ['A', 'D', 'S', 'C', 'H'] 
    for q in move_order: 
        if q not in moves: 
            return False 
    return True 

您以递归方式编写了 check_correct_moves_only,这对于您的问题而言是不可取的。您还应该仅在真正需要时才使用 global 变量。在大多数情况下,使用参数更具可读性。如果您需要在单独调用的不同方法中使用某些信息,您也可以编写一个 class 来代替。