Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python a[:]=b和a=b[:]之间有什么区别_Python_List_Slice - Fatal编程技术网

Python a[:]=b和a=b[:]之间有什么区别

Python a[:]=b和a=b[:]之间有什么区别,python,list,slice,Python,List,Slice,这两种说法有什么区别 a=[1,2,3] b=[4,5,6] c=[] d=[] 但两者都给出了相同的结果 c是[1,2,3],d是[4,5,6] 在功能方面有什么区别吗?没有太大区别c[:]=a更新c就地引用的列表d=b[:]创建一个新列表,它是b的副本(忘记了在第4行创建的旧列表)。在大多数应用程序中,除非对周围的数组有其他引用,否则不太可能看到差异。当然,对于c[:]=…版本,您必须已经有了一个列表c。c[:]=a这意味着用a的元素替换c的所有元素 c[:]=a d=b[:] d=b[

这两种说法有什么区别

a=[1,2,3]
b=[4,5,6]
c=[]
d=[]
但两者都给出了相同的结果

c是[1,2,3],d是[4,5,6]


在功能方面有什么区别吗?

没有太大区别
c[:]=a
更新
c
就地引用的列表
d=b[:]
创建一个新列表,它是b的副本(忘记了在第4行创建的旧列表)。在大多数应用程序中,除非对周围的数组有其他引用,否则不太可能看到差异。当然,对于
c[:]=…
版本,您必须已经有了一个列表
c

c[:]=a
这意味着用a的元素替换c的所有元素

c[:]=a
d=b[:]
d=b[:]
表示创建b的浅拷贝,并将其分配给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]]
另一方面:

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])

非常雄辩地说。(+1来自我)在功能方面有什么不同吗?@InternalServerError——这取决于。你有其他关于
c
的参考资料吗?这些引用也将看到更改。考虑:
c=[];f=c;c[:]=a
--现在
f
也将具有与
a
相同的元素,因为
f
c
是同一个列表。你的意思是a的变化会影响c和f吗?@GrijeshChauhan我从两本书中学习,但从伟人身上学到了很多东西。
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])
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