【问题标题】:Function overwriting list passed in as argument - Python作为参数传入的函数覆盖列表 - Python
【发布时间】:2020-09-04 06:02:27
【问题描述】:

我正在编写一个程序来玩井字游戏(我正在学习 python)。我有一个函数,它传入一个名为 movelist 的 10 项列表,然后检查是否有任何玩家,无论是 Xs 还是 Os 赢得了比赛。如果其中一个获胜,则返回“X”或“O”,如果没有人获胜,则返回 False。 wins 是所有可能获胜组合的列表。但是该函数正在覆盖移动列表,我不知道为什么。我将 movelist 分配给测试,然后迭代并更改测试,所以我不明白 movelist 在哪里/为什么被更改。传入的典型移动列表是 ['#','X','X','X',4,'O',6,7,'O',9]。该函数根本不应该更改列表“movelist”,因为它会覆盖之前已经做出的动作并使游戏无法玩。 请看下面的代码:

def gamewon(movelist):

    #WINNING COMBINATIONS
    wins = [['N','Y','Y','Y','N','N','N','N','N','N'],['N','N','N','N','Y','Y','Y','N','N','N'],
            ['N','N','N','N','N','N','N','Y','Y','Y'],['N','Y','N','N','Y','N','N','Y','N','N'],
            ['N','N','Y','N','N','Y','N','N','Y','N'],['N','N','N','Y','N','N','Y','N','N','Y'],
            ['N','Y','N','N','N','Y','N','N','N','Y'],['N','N','N','Y','N','Y','N','Y','N','N']]

    test = movelist
    index = 0
    for item in test:
        if item == 'X':
            test[index] = 'Y'
            index += 1
        else:
            test[index] = 'N'
            index += 1

    if test in wins:
        return 'X'

    test = movelist
    index = 0

    for item in test:
        if item == 'O':
            test[index] = 'Y'
            index += 1
        else:
            test[index] = 'N'
            index += 1

    if test in wins:
        return 'O'

    return False

【问题讨论】:

  • nedbatchelder.com/text/names.htmltest = movelist复制test。它只是使 test 成为对同一列表的第二次引用,因此您正在修改原始列表。

标签: python list overwrite


【解决方案1】:

我认为您遇到的问题是您应该使用test = movelist.copy() 而不是test = movelist。这是 python 中的一个常见问题,也是 python 3 中列表功能的一部分。同样的问题也可能出现在字典中,它也有 .copy() 方法。希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 2016-05-27
    • 2012-04-03
    • 1970-01-01
    • 2015-12-27
    • 2017-07-12
    • 1970-01-01
    • 2011-02-13
    • 2021-03-18
    • 1970-01-01
    相关资源
    最近更新 更多