只有循环的最后一次迭代存储在python中我2d数组的每个索引处

时间:2018-11-16 05:21:20

标签: python

我正在尝试使用嵌套的for循环在python中创建2d数组。 这是我的代码:

count = 0
stateArray = []
state = [0]*2
for i in range (0,2):
    for j in range(0,2):
        state[0] = i
        state[1] = j
        stateArray.append(state)
        print (count)
        print (stateArray[count])
        count += 1
print(stateArray[0])
print(stateArray[1])
print(stateArray[2])

这是我的输出:

0
[0, 0]
1
[0, 1]
2
[1, 0]
3
[1, 1]
[1, 1]
[1, 1]
[1, 1]

退出循环后,为什么stateArray更改为在每个索引处存储fo循环的最后一次迭代?

1 个答案:

答案 0 :(得分:0)

我认为您需要:

count = 0
stateArray = []
# state = [0]*2
for i in range (0,2):
    for j in range(0,2):
        # state[0] = i
        # state[1] = j
        stateArray.append([i,j])
        print (count)
        print (stateArray[count])
        count += 1
print(stateArray[0])
print(stateArray[1])
print(stateArray[2])

输出:

0
[0, 0]
1
[0, 1]
2
[1, 0]
3
[1, 1]
[0, 0]
[0, 1]
[1, 0]