简体   繁体   English

从功能返回列表后,为什么列表变为空?

[英]Why does list become empty after returning it from function?

When returning a list of tuples from a class method, the returned list becomes empty. 从类方法返回元组列表时,返回的列表为空。

I have tried printing the list to sys.stderr just before returning it (here, it contains all the tuples) and after receiving it on the calling side (here, all tuples are gone). 我试过在返回列表之前(在这里,它包含所有元组)以及在调用方接收到它之后(在这里,所有元组都消失了),将列表打印到sys.stderr。 I have also tried changing data type to a tuple of tuples, but the problem remains. 我也尝试过将数据类型更改为元组的元组,但是问题仍然存在。 I have double checked so that I am returning the correct variable. 我已仔细检查过,以便返回正确的变量。 There are no similar variable names, but I have also tried changing the variable name without success. 没有类似的变量名,但是我也曾尝试更改变量名而没有成功。

I am running my code on Python 3 in Codeingame's environment. 我正在Codeingame的环境中在Python 3上运行代码。 This is the specific challenge I am coding for: https://www.codingame.com/ide/puzzle/tic-tac-toe 这是我正在编码的特定挑战: https : //www.codingame.com/ide/puzzle/tic-tac-toe

class Boardstate:
    def get_valid_moves(self):
        valid_moves = []
        for row in range(3):
            for col in range(3):
                sq = self.squares[row][col]
                sq_valid_moves = [
                    (row*3 + j, col*3 + i) for (j, i) in sq.get_valid_moves()
                ]
                valid_moves.extend(sq_valid_moves)
        print(valid_moves, file=sys.stderr)
        return valid_moves

valid_moves = temp_state.get_valid_moves() #temp_state is an instance of Boardstate
print(valid_moves, file=sys.stderr)

I expect to see the same list of tuples outside the class method as I see inside it before returning. 我希望在类方法外看到与在返回之前相同的元组列表。

Try with adding self to valid_moves like this: 尝试将self添加到valid_moves中,如下所示:

class Boardstate:
    def get_valid_moves(self):
        self.valid_moves = []
        for row in range(3):
            for col in range(3):
                sq = self.squares[row][col]
                sq_valid_moves = [
                    (row*3 + j, col*3 + i) for (j, i) in sq.get_valid_moves()
                ]
                self.valid_moves.extend(sq_valid_moves)
        print(self.valid_moves, file=sys.stderr)
        return self.valid_moves

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

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