简体   繁体   English

Function 覆盖列表作为参数传入 - Python

[英]Function overwriting list passed in as argument - Python

I'm writing a program to play a game of Tic Tac Toe (I'm learning python).我正在编写一个程序来玩井字游戏(我正在学习 python)。 I have a function that gets a 10 item list called movelist passed in, which is then checks to see if any player, either Xs or Os has won the game.我有一个 function 传入一个名为 movelist 的 10 项列表,然后检查是否有任何玩家,无论是 Xs 还是 Os 赢得了比赛。 If one of them has, it returns 'X' or 'O', if no one has won it returns False.如果其中一个获胜,则返回“X”或“O”,如果没有人获胜,则返回 False。 wins is a list of all possible winning combinations. wins 是所有可能获胜组合的列表。 However the function is overwriting the movelist and I can't figure out why.但是 function 正在覆盖移动列表,我不知道为什么。 I assign movelist to test and then iterate through and change test, so I don't understand where/why movelist has been changed.我将 movelist 分配给测试,然后迭代并更改测试,所以我不明白 movelist 在哪里/为什么被更改。 A typical movelist being passed in would be ['#','X','X','X',4,'O',6,7,'O',9].传入的典型移动列表是 ['#','X','X','X',4,'O',6,7,'O',9]。 The function should not change the list 'movelist' at all, as it overwrites previous moves that have been made and makes the game unplayable. function 根本不应该更改列表“movelist”,因为它会覆盖之前已经做出的动作并使游戏无法玩。 Please see code below:请看下面的代码:

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

I think the problem your having is that you should be using test = movelist.copy() rather than test = movelist .我认为您遇到的问题是您应该使用test = movelist.copy()而不是test = movelist This is a common problem in python and is part of how lists function in python 3. The same problem can occur with dictionaries, which also have .copy() methods.这是 python 中的常见问题,并且是如何在 python 3 中列出 function 的方式的一部分。同样的问题也可能出现在具有.copy()方法的字典中。 Hope that helps.希望有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM