a=[1,2,3]
b=[4,5,6]
c=[]
d=[]
這兩個聲明有什麼區別?a [:] = b和a = b之間的區別是什麼?
c[:]=a
d=b[:]
但是兩者都給出相同的結果。
c爲[1,2,3],d爲[4,5,6]
而沒有任何區別的功能明智?
a=[1,2,3]
b=[4,5,6]
c=[]
d=[]
這兩個聲明有什麼區別?a [:] = b和a = b之間的區別是什麼?
c[:]=a
d=b[:]
但是兩者都給出相同的結果。
c爲[1,2,3],d爲[4,5,6]
而沒有任何區別的功能明智?
c[:] = a
它意味着替換C的所有元件由一個
>>> l = [1,2,3,4,5]
>>> l[::2] = [0, 0, 0] #you can also replace only particular elements using this
>>> l
[0, 2, 0, 4, 0]
>>> k = [1,2,3,4,5]
>>> g = ['a','b','c','d']
>>> g[:2] = k[:2] # only replace first 2 elements
>>> g
[1, 2, 'c', 'd']
>>> a = [[1,2,3],[4,5,6],[7,8,9]]
>>> c[:] = a #creates a shallow copy
>>> a[0].append('foo') #changing a mutable object inside a changes it in c too
>>> a
[[1, 2, 3, 'foo'], [4, 5, 6], [7, 8, 9]]
>>> c
[[1, 2, 3, 'foo'], [4, 5, 6], [7, 8, 9]]
d = b[:]
裝置元件創建的B A 淺拷貝並將其分配給d,它類似於d = list(b)
>>> l = [1,2,3,4,5]
>>> m = [1,2,3]
>>> l = m[::-1]
>>> l
[3,2,1]
>>> l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> m = l[:] #creates a shallow copy
>>> l[0].pop(1) # a mutable object inside l is changed, it affects both l and m
2
>>> l
[[1, 3], [4, 5, 6], [7, 8, 9]]
>>> m
[[1, 3], [4, 5, 6], [7, 8, 9]]
沒有太大的區別。 c[:]=a
更新c
提到的列表。 d=b[:]
創建一個新的列表,它是b的副本(忘記您在第4行創建的舊列表)。在大多數應用程序中,除非您有其他引用數組的參考,否則不太可能會看到差異。當然,在c[:]=...
版本中,您必須已經有一個名單c
。
Ashwini說什麼。 :)我會詳細說明一點點:
In [1]: a=[1,2,3]
In [2]: b = a
In [3]: c = a[:]
In [4]: b, c
Out[4]: ([1, 2, 3], [1, 2, 3])
In [5]: a is b, a is c
Out[5]: (True, False)
另一路:
In [1]: a = [1,2,3]
In [2]: aold = a
In [3]: a[:] = [4,5,6]
In [4]: a, aold
Out[4]: ([4, 5, 6], [4, 5, 6])
In [5]: a = [7,8,9]
In [6]: a, aold
Out[6]: ([7, 8, 9], [4, 5, 6])
看看會發生什麼?
Ashwini's answer準確地描述發生了什麼,這裏有兩個方法之間的差異的幾個例子:
a=[1,2,3]
b=[4,5,6]
c=[]
c2=c
d=[]
d2=d
c[:]=a # replace all the elements of c by elements of a
assert c2 is c # c and c2 should still be the same list
c2.append(4) # modifying c2 will also modify c
assert c == c2 == [1,2,3,4]
assert c is not a # c and a are not the same list
d=b[:] # create a copy of b and assign it to d
assert d2 is not d # d and d2 are no longer the same list
assert d == [4,5,6] and d2 == [] # d2 is still an empty list
assert d is not b # d and b are not the same list
非常雄辯地說明。 (從我+1) – mgilson
+1非常簡潔和明確的解釋 – Levon
有什麼區別功能明智嗎? –