a [:] = b和a = b [:]有什么区别 [英] What is the difference between a[:]=b and a=b[:]
本文介绍了a [:] = b和a = b [:]有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
a=[1,2,3]
b=[4,5,6]
c=[]
d=[]
这两个语句之间有什么区别?
Whats the difference between these two statements?
c[:]=a
d=b[:]
但是两者给出的结果相同.
But both gives the same result.
c为[1,2,3],d为[4,5,6]
c is [1,2,3] and d is [4,5,6]
功能上有什么区别吗?
推荐答案
c[:] = a
表示将c的所有元素替换为a的元素
c[:] = a
it means replace all the elements of c by elements of a
>>> 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的浅副本并将其分配给d,它类似于d = list(b)
d = b[:]
means create a shallow copy of b and assign it to d , it is similar to 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]]
这篇关于a [:] = b和a = b [:]有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文