简体   繁体   English

为什么元组或列表中的最后一个值索引给出不同的 class 而切片在 python 中给出不同的值?

[英]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.

相关问题 Numpy:为什么使用列表和 numpy 数组对 &gt; 2 维数组进行高级索引会给出不同的结果 - Numpy: Why advance indexing of > 2 dimensional arrays with a list and numpy array give different results 为什么不同的百分位数给出相同的值? - Why do different percentiles give the same value? 为什么解包在 Python 中给出一个列表而不是一个元组? - Why does unpacking give a list instead of a tuple in Python? last() 和 [] 运算符给出不同的结果 - last() and [] operator give different results 不同的Python最小化函数给出不同的值,为什么? - Different Python minimization functions give different values, Why? 为什么在 f 字符串中索引匿名元组会出错? - Why does indexing anonymous tuple in f-string give an error? 如果先前生成的值被显式设置为新种子,为什么Python random.random()会给出不同的值? - Why does the Python random.random() give a different value if the previously generated value is explicitly set as the new seed? 当我想在 Python 中将字典添加到列表中时,为什么 append() 和 += 会给出不同的结果? - Why does append() and += give different results when I want to add a dictionary into a list in Python? numpy数组索引:列表索引和np.array索引给出不同的结果 - numpy array indexing: list index and np.array index give different result 为什么 date_range 给出的结果与 DataFrame Pandas 日期的索引 [] 不同? - Why does date_range give a result different from indexing [] for DataFrame Pandas dates?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM