[:] 在 python 中是什么意思? [英] What does [:] mean in python?

查看:145
本文介绍了[:] 在 python 中是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如如果 tableState 是一个元组,并且我们声明了一个变量:

e.g. if tableState is a tuple, and we're declaring a variable:

x = tableState[1][:]

[:] 是什么意思?

推荐答案

它需要元组的副本,而不是对元组本身的引用.

It takes a copy of the tuple, instead of a reference to the tuple itself.

[:] 语法是一个带有默认开始和结束值(0 和列表的长度)的切片,返回一个带有这些索引的新元组,因此有效地是内容.

The [:] syntax is a slice with the default start and end values (0 and the length of the list), returning a new tuple with those indices, so effectively an exact copy of the contents.

对于元组,这没有多大意义,因为元组是不可变的.您可以安全地传递对元组的引用,而无需更改其索引所引用的内容.

For tuples, this doesn't make much sense, because tuples are immutable. You can safely pass around references to a tuple without changing what it's indices refer to.

不过,它对列表的作用相同.您通常需要创建一个列表的副本才能修改内容,而使用默认的所有元素"切片是一种很好、简洁且快速的方法.

It works the same for lists, though. You often need to create a copy of a list to be able to modify the contents, and using the default 'all elements' slice is a nice, concise and fast method of doing just that.

这篇关于[:] 在 python 中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆