的預先複製列表它已經有一段時間,因爲我用Python的,而這一次我真的不明白: - 我做字符串M1 名單 - 我把它複製到M2 - 然後我使用M1中的re.sub將「e」更改爲「E」 - M2也改變了!應用re.sub也改變串
下面是一些有興趣的thos代碼。它在Anaconda2和Python 3.6.0上都顯示了這種行爲。
import re
# Normal operation on single strings
m1 = "Hello."
m2 = m1
m1 = re.sub("e", "E", m1)
print(m1)
print(m2)
print("")
# Normal operation on one list of strings
M = ["Hello.", "Bye-bye!"]
for i in range(len(M)):
M[i] = re.sub("e", "E", M[i])
print (M)
print("")
# Unexpected behaviour on a copied list of strings
M1 = ["Hello.", "Bye-bye!"]
M2 = M1
for i in range(len(M1)):
M1[i] = re.sub("e", "E", M1[i])
print(M1)
print(M2)
M2 = M1並沒有提供一個新的字符串內容相同,它只是對舊的字符串的引用。使用例如deepcopy() – Humbalan
超級!我不知道Python可以像這樣的指針工作。我猜,我有時間閱讀一些Python理論。 – user3766450