我正在尝试编写一个游戏,其中有一个3x3网格(考虑零和交叉US=Tic战术脚趾)。
每个单元格都有一个权重。当玩家放置一个计数器时,就会计算出一个分数。我希望我的代码遍历3x3矩阵,找到最高分数,并返回找到最高分数的单元格的坐标(这是可行的)-但如果有几个单元格具有相同的最高分数,我希望返回一个列表,其中包含找到该分数的每个位置。
下面是我的代码的精简版本(有许多print语句试图找出它不能工作的原因)。
其目的是让循环记录一个简单的列表("pos"),该列表具有行和列坐标(例如)并将其附加到相等分数(“可能性”)的运行列表中
如果不是尝试添加一个包含两个条目的列表,而是添加一个随机数,则整个列表("possibles")将按预期构建,但添加包含两个条目的列表将导致最终位置的重复列表(请参见输出)。
我显然有逻辑上的问题,但我是Python的新手。有人能告诉我哪里出错了吗?
def test():
val = 1
max_val = 0
possibles = [] # This is the list where I will store a list of equally weighted positions
pos = [] # This is simply a 2 number co-ordinate
pos.append("") # Get it ready for row & col references
pos.append("")
for row in range (0,3):
for col in range (0,3):
print("Testing row",row,"col",col)
print("Possibles so far",possibles)
print("Pos=",pos)
pos[0] = row
pos[1] = col
print("Now pos=",pos)
#possibles.append(randint(0,100)) # This works
possibles.append(pos) # This doesn't
print("List of equals",possibles)
test()输出:
Testing row 0 col 0
Possibles so far []
Pos= ['', '']
Now pos= [0, 0]
Testing row 0 col 1
Possibles so far [[0, 0]]
Pos= [0, 0]
Now pos= [0, 1]
Testing row 0 col 2
Possibles so far [[0, 1], [0, 1]]
Pos= [0, 1]
Now pos= [0, 2]
Testing row 1 col 0
Possibles so far [[0, 2], [0, 2], [0, 2]]
Pos= [0, 2]
Now pos= [1, 0]
Testing row 1 col 1
Possibles so far [[1, 0], [1, 0], [1, 0], [1, 0]]
Pos= [1, 0]
Now pos= [1, 1]
Testing row 1 col 2
Possibles so far [[1, 1], [1, 1], [1, 1], [1, 1], [1, 1]]
Pos= [1, 1]
Now pos= [1, 2]
Testing row 2 col 0
Possibles so far [[1, 2], [1, 2], [1, 2], [1, 2], [1, 2], [1, 2]]
Pos= [1, 2]
Now pos= [2, 0]
Testing row 2 col 1
Possibles so far [[2, 0], [2, 0], [2, 0], [2, 0], [2, 0], [2, 0], [2, 0]]
Pos= [2, 0]
Now pos= [2, 1]
Testing row 2 col 2
Possibles so far [[2, 1], [2, 1], [2, 1], [2, 1], [2, 1], [2, 1], [2, 1], [2, 1]]
Pos= [2, 1]
Now pos= [2, 2]
List of equals [[2, 2], [2, 2], [2, 2], [2, 2], [2, 2], [2, 2], [2, 2], [2, 2], [2, 2]]发布于 2017-12-14 22:12:21
您一次又一次地将相同的对象pos追加到列表中。如果在下一次循环中更改其值,则其所有表示形式也将更改。您可以测试这个。在test函数的末尾追加:
for item in possibles:
print(item, id(item))看,所有列表项都有相同的id。
要避免这种情况,请在每个循环中分配一个新对象:
def test():
possibles = []
for row in range (3):
for col in range (3):
pos = [row, col] #create a new list
print("Now pos=",pos)
possibles.append(pos) #and append this new element
print("List of equals",possibles)
test()它看起来很相似,但不是更改现有列表pos的元素[0]和[1],而是在每个循环中创建一个新的列表。如果用上面的id(item)检查,possibles的所有列表元素现在都有一个不同的id。
https://stackoverflow.com/questions/47813798
复制相似问题