简体   繁体   English

[:]如何在python中工作?

[英]How does [:] work in python?

It copies a list right? 它复制一份清单吧? but in the code I'm looking at its x = x[:] which I don't understand. 但在代码中我正在看它的x = x[:]我不明白。 How can both copies be called the same thing? 如何将两个副本称为同一个东西?

The right is evaluated first, placed into a temporary variable, and x is re-assigned to the temp variable. 首先评估权限,将其置于临时变量中,并将x重新分配给临时变量。 You never see it, of course. 当然,你永远不会看到它。

To answer your question "How does [:] work in python?" 回答你的问题“[:]如何在python中工作?” is a bit tricky in the context of this particular expression by itself 在这个特定的表达本身的背景下有点棘手

x = x[:]

which isn't that likely to occur as it's really like saying a = a . 这不太可能发生,因为它真的像是说a = a

You are more likely to see something like 你更有可能看到类似的东西

a = x[:]

which in simple words makes a copy of the list referred to by x and assigns it to a . 用简单的单词表示x引用的列表的副本并将其分配给a

If you simply did 如果你只是这样做

a = x

both variables would refer to the same location, and any change to either of the variables would be reflected in both. 两个变量都将引用相同的位置,并且对任一变量的任何更改都将反映在两者中。

Here is what happens if you don't use the colon notation, eg, a = x : 如果您不使用冒号表示法会发生以下情况,例如a = x

In [31]: x = range(5)
In [32]: a = x

In [33]: a
Out[33]: [0, 1, 2, 3, 4]

In [34]: x
Out[34]: [0, 1, 2, 3, 4]

In [35]: a[3] = 99    # I am making a change in a

In [36]: a
Out[36]: [0, 1, 2, 99, 4]

In [37]: x
Out[37]: [0, 1, 2, 99, 4]   # but x changes too!

Compare this with a = x[:] 将其与a = x[:]

In [38]: x = range(5)
In [39]: a = x[:]

In [40]: a
Out[40]: [0, 1, 2, 3, 4]

In [41]: x
Out[41]: [0, 1, 2, 3, 4]

In [42]: a[3] = -99    

In [43]: a
Out[43]: [0, 1, 2, -99, 4]  # a changes

In [44]: x
Out[44]: [0, 1, 2, 3, 4]    # x does not change

Note: @gnibbler provides a short and complete example (below in the comments) where you might encounter x = x[:] and in that context that assignment would serve a useful purpose (though we don't know in what context you came across this originally). 注意:@gnibbler提供了一个简短而完整的示例(在评论中如下),您可能会遇到x = x[:]并且在该上下文中,赋值将有用(尽管我们不知道您遇到的上下文)这最初)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM