0
我在python中編寫了下面的代碼。在checkd, 當我更新d [II] [JJ],似乎如果編譯器會爲自己的自由,使1。以下所有列條目Python中的數組更新異常
代碼:
def checkd(d, level, a, b):
i = len(b)
j = len(a)
print ['0'] + list(a)
for ii in range(i):
for jj in range(j):
if a[jj] == b[ii]:
#print a[jj] +" "+ b[ii] + " Matched."
d[ii][jj] = 1
print b[ii] + "\t" + a[jj] + "\t" + str(d[ii][jj])
print [b[ii]] + [str(m) for m in d[ii]]
return d
a = raw_input("First word:")
b = raw_input("Second word:")
w = input("Size of words to check:")
d = [[0]*len(a)]*len(b)
d = checkd(d, w, a, b)
print d
for x in d : print x
輸出:
First word:ascend
Second word:nd
Size of words to check:2
['0', 'a', 's', 'c', 'e', 'n', 'd']
n a 0
n s 0
n c 0
n e 0
n n 1
n d 0
['n', '0', '0', '0', '0', '1', '0']
d a 0
d s 0
d c 0
d e 0
d n 1
d d 1
['d', '0', '0', '0', '0', '1', '1']
[[0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 1, 1]]
[0, 0, 0, 0, 1, 1]
[0, 0, 0, 0, 1, 1]
正如你會發現,這不僅導致一些隨機匹配(d,N,1?!)的「d」行中, 返回的二維數組只是最後一行的副本在函數中的一個。
我有一些Python的經驗。如果可能的話,我不是在尋找解決方法(不是我介意),而是解釋這種行爲?
謝謝!
非常感謝。幾分鐘後我找到了答案: http://stackoverflow.com/questions/240178/unexpected-feature-in-a-python-list-of-lists – 2013-02-22 10:14:41