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

标签 python list iterable

所以我有这个来获取用户的输入(刚刚学习 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 来代替。

关于Python:在继续之前完成对列表的迭代检查?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31008541/

相关文章:

python - 使用上下文管理器控制流程

java - 简单的 Java 列表问题

java - Junit 实现 Iterable

java - 为什么我的二叉搜索树不会显示超过 3 个节点?

python - 在 matplotlib 中自定义颜色 - 热图

python - 如何从 pandas 中的日期和时间列添加时间索引

javascript - Django Rest 框架正在从数据库中返回 'u 前缀到 Angular

通过索引存储对象的Java类

java - 从 javadoc 澄清集合的二进制搜索性能声明

java - 将流变成可迭代?