Python 相同列表列出不同的输出
我需要创建一个列表作为两个变量的函数,但该列表的输出与手动创建的另一个列表的输出不同(两个列表相等) 代码如下:Python 相同列表列出不同的输出,python,list,Python,List,我需要创建一个列表作为两个变量的函数,但该列表的输出与手动创建的另一个列表的输出不同(两个列表相等) 代码如下: from math import factorial n=4 k=3 ntuples=int(factorial(n-1)/factorial(k-1)) B=[[1]*k]*ntuples A=[[1,1,1],[1,1,1],[1,1,1]] print(A==B) m=0 n=0 for i in range(len(A)): A[i][m]=A[i][m]+1
from math import factorial
n=4
k=3
ntuples=int(factorial(n-1)/factorial(k-1))
B=[[1]*k]*ntuples
A=[[1,1,1],[1,1,1],[1,1,1]]
print(A==B)
m=0
n=0
for i in range(len(A)):
A[i][m]=A[i][m]+1
m+=1
for j in range(len(B)):
B[j][n]=B[j][n]+1
n+=1
print(A)
print(B)
output:
True
[[2, 1, 1], [1, 2, 1], [1, 1, 2]]
[[2, 2, 2], [2, 2, 2], [2, 2, 2]]
我想得到A的输出,但使用B列表。我做错了什么?谢谢 当你像这样初始化一个矩阵时:
B=[[1]*k]*ntuples
,如果一个值被改变,所有其他值都会改变。下面是一个例子:
>>> B
[[1, 1, 1], [1, 1, 1], [1, 1, 1]]
>>> B[0][0]
1
>>> B[1][0]
1
>>> B[0][0] = 0
>>> B[0][0]
0
>>> B[1][0]
0
>>> B[2][0]
0
>>> B
[[0, 1, 1], [0, 1, 1], [0, 1, 1]]
为了避免这种情况,您可以使用numpy
:
import numpy as np
B=np.ones((ntuples,ntuples),dtype = int)
完整代码:
from math import factorial
n=4
k=3
import numpy as np
ntuples=int(factorial(n-1)/factorial(k-1))
B=np.ones((ntuples,ntuples),dtype = int)
A=[[1,1,1],[1,1,1],[1,1,1]]
print(A==B)
m=0
n=0
for i in range(len(A)):
A[i][m]=A[i][m]+1
m+=1
for j in range(len(B)):
B[j][n]=B[j][n]+1
n+=1
print(A)
print(B)
输出:
[[ True True True]
[ True True True]
[ True True True]]
[[2, 1, 1], [1, 2, 1], [1, 1, 2]]
[[2 1 1]
[1 2 1]
[1 1 2]]
True
[[2, 1, 1], [1, 2, 1], [1, 1, 2]]
[[2, 1, 1], [1, 2, 1], [1, 1, 2]]
如果您不想使用numpy
,那么也可以使用列表来实现相同的结果。只需将B=np.ones((ntuples,ntuples),dtype=int)
替换为以下行:
B=[[1,1,1] for x in range(ntuples)]
输出:
[[ True True True]
[ True True True]
[ True True True]]
[[2, 1, 1], [1, 2, 1], [1, 1, 2]]
[[2 1 1]
[1 2 1]
[1 1 2]]
True
[[2, 1, 1], [1, 2, 1], [1, 1, 2]]
[[2, 1, 1], [1, 2, 1], [1, 1, 2]]