[英]What are the differences between these two lines?
friends = my[:] #1
friends[:] = my #2
both variables can be list or string, ie iterable.两个变量都可以是列表或字符串,即可迭代。 I am learning python.
我正在学习 python。
The first line rebinds friends
to a new sequence that is a shallow copy of my
(really, it can do anything, but assuming my
isn't a memoryview
or a weird third party type like a numpy
array, that's usually a shallow copy of the whole sequence).第一行将
friends
重新绑定到一个新序列,该序列是my
的浅拷贝(真的,它可以做任何事情,但假设my
不是memoryview
或像numpy
数组这样的奇怪第三方类型,那通常是整个序列)。
The second line reassigns the contents of friends
(which must be mutable) to whatever is in the iterable my
(again, weird overrides of friends
can change this);第二行将
friends
的内容(必须是可变的)重新分配给可迭代my
中的任何内容(同样,奇怪的friends
覆盖可以改变这一点); my
need not be a sequence, a plain iterator would also work, and would be exhausted in the process of populating friends
. my
不需要是一个序列,一个普通的迭代器也可以工作,并且会在填充friends
的过程中耗尽。
In both cases it's a shallow copy (reassigning or appending/popping elements in my
after either line won't change friends
).在这两种情况下,它都是一个浅拷贝(在
my
任何一行之后重新分配或附加/弹出元素都不会改变friends
)。 The main difference is that the first line is a rebinding to a new sequence, while the latter changes friends
in place.主要区别在于第一行是对新序列的重新绑定,而后者是在原地更改
friends
。 This is important in two ways:这在两个方面很重要:
friends
, the first option doesn't affect the alias (rebinding discards the old reference, so the other aliases keep it, friends
doesn't), while the second option modifies the other aliasesfriends
相同的序列,第一个选项不会影响别名(重新绑定会丢弃旧引用,因此其他别名保留它, friends
不会),而第二个选项修改其他别名friends
, it just replaces the contents.friends
的类型,只是替换内容。 The first option doesn't care what friends
used to be (it could be a non-sequence like int
), it ends up as whatever the slicing produces (eg if my
is a list
, friends
becomes a list
afterward).friends
是什么(它可能是像int
这样的非序列),它最终会成为切片产生的任何东西(例如,如果my
是一个list
,那么之后friends
会成为一个list
)。 A concrete example using this setup:使用此设置的具体示例:
friends = [1, 2, 3]
alsofriends = friends
my = (4, 5, 6)
If you use line 1, then after that line, friends
is (4, 5, 6)
, and alsofriends
is still [1, 2, 3]
(it's not related to friends
anymore).如果你使用第 1 行,那么在那一行之后,
friends
是(4, 5, 6)
,而且alsofriends
仍然是[1, 2, 3]
(它不再与friends
相关)。
If you use line 2, then after that line, friends
is [4, 5, 6]
(contents from my
, but still a list
), and alsofriends
is now [4, 5, 6]
as well (it's still an alias of friends
, and the contents of the shared list
now match what was copied from my
).如果你使用第 2 行,那么在那一行之后,
friends
是[4, 5, 6]
(来自my
的内容,但仍然是一个list
),而且现在的alsofriends
也是[4, 5, 6]
(它仍然是friends
,并且共享list
的内容现在与从my
复制的内容匹配)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.