[英]Why the last value indexing in tuple or list give different class and slicing give different in python?
For eg if例如,如果
a=(1,[2,3])
Then indexing然后索引
b=a[1]
will give class list (because index value is list)将给出 class列表(因为索引值是列表)
[2, 3] <class 'list'>
but while slicing但是在切片时
c=a[1:]
give the class tuple给出 class元组
([2, 3],) <class 'tuple'>
Can anyone explain why this is so?谁能解释为什么会这样? How does Python differentiate indexing from slicing in regards to determining class?
在确定 class 方面,Python 如何区分索引和切片?
Thank you in advance.先感谢您。
Indexing gives you a specific item within the sequence, while slicing returns a segment thereof, even if that segment is one element long.索引为您提供序列中的特定项目,而切片返回其中的一个片段,即使该片段是一个元素长。
A tuple consists of a number of arbitrary objects/heterogeneous items which support indexing and slicing operations.元组由许多支持索引和切片操作的任意对象/异构项组成。
The following will always give you a tuple:以下将始终为您提供一个元组:
t = tuple()
t[start:stop]
t[start:]
t[:stop]
t[:]
If you'll use indices to access objects in tuple
like t[0]
or t[-1]
then the type will be different for different indices depending on what is present on that specific index.如果您将使用索引来访问像
t[0]
或t[-1]
这样的tuple
中的对象,那么不同索引的类型将有所不同,具体取决于该特定索引上存在的内容。
Slicing returns a slice of a sequence (ie the same type), while indexing returns the item at that index.切片返回序列的切片(即相同类型),而索引返回该索引处的项目。 Compare:
相比:
>>> t = [1, 2, 3]
>>> t[1:] # Slice -> list
[2, 3]
>>> t[1] # Index -> int
2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.