理解切片符号

2024-04-25 08:07:37 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
3条回答

Python tutorial谈到了这个问题(向下滚动一点,直到找到关于切片的部分)。

ASCII艺术图也有助于记住切片的工作方式:

 +---+---+---+---+---+---+
 | P | y | t | h | o | n |
 +---+---+---+---+---+---+
 0   1   2   3   4   5   6
-6  -5  -4  -3  -2  -1

One way to remember how slices work is to think of the indices as pointing between characters, with the left edge of the first character numbered 0. Then the right edge of the last character of a string of n characters has index n.

列举语法允许的可能性:

>>> seq[:]                # [seq[0],   seq[1],          ..., seq[-1]    ]
>>> seq[low:]             # [seq[low], seq[low+1],      ..., seq[-1]    ]
>>> seq[:high]            # [seq[0],   seq[1],          ..., seq[high-1]]
>>> seq[low:high]         # [seq[low], seq[low+1],      ..., seq[high-1]]
>>> seq[::stride]         # [seq[0],   seq[stride],     ..., seq[-1]    ]
>>> seq[low::stride]      # [seq[low], seq[low+stride], ..., seq[-1]    ]
>>> seq[:high:stride]     # [seq[0],   seq[stride],     ..., seq[high-1]]
>>> seq[low:high:stride]  # [seq[low], seq[low+stride], ..., seq[high-1]]

当然,如果(high-low)%stride != 0,那么终点将略低于high-1

如果stride是负数,则在倒数后顺序会有一点变化:

>>> seq[::-stride]        # [seq[-1],   seq[-1-stride],   ..., seq[0]    ]
>>> seq[high::-stride]    # [seq[high], seq[high-stride], ..., seq[0]    ]
>>> seq[:low:-stride]     # [seq[-1],   seq[-1-stride],   ..., seq[low+1]]
>>> seq[high:low:-stride] # [seq[high], seq[high-stride], ..., seq[low+1]]

扩展切片(带逗号和省略号)通常只用于特殊的数据结构(如NumPy);基本序列不支持它们。

>>> class slicee:
...     def __getitem__(self, item):
...         return repr(item)
...
>>> slicee()[0, 1:2, ::5, ...]
'(0, slice(1, 2, None), slice(None, None, 5), Ellipsis)'

很简单真的:

a[start:stop]  # items start through stop-1
a[start:]      # items start through the rest of the array
a[:stop]       # items from the beginning through stop-1
a[:]           # a copy of the whole array

还有一个step值,可以与以上任何一个一起使用:

a[start:stop:step] # start through not past stop, by step

要记住的关键点是:stop值表示所选切片中的第一个值而不是。因此,stopstart之间的区别是所选元素的数量(如果step是1,则为默认值)。

另一个特点是startstop可能是一个负的数,这意味着它从数组的末尾而不是开头开始计数。所以:

a[-1]    # last item in the array
a[-2:]   # last two items in the array
a[:-2]   # everything except the last two items

类似地,step可能是负数:

a[::-1]    # all items in the array, reversed
a[1::-1]   # the first two items, reversed
a[:-3:-1]  # the last two items, reversed
a[-3::-1]  # everything except the last two items, reversed

如果项目比您要求的少,Python对程序员很好。例如,如果要求a[:-2],而a只包含一个元素,则会得到一个空列表而不是一个错误。有时你更喜欢错误,所以你必须意识到这可能发生。

slice()对象

的关系

切片运算符[]实际上在上述代码中与使用:符号的slice()对象一起使用(仅在[]内有效),即:

a[start:stop:step]

相当于:

a[slice(start, stop, step)]

Slice对象的行为也略有不同,这取决于参数的数量,类似于range(),即支持slice(stop)slice(start, stop[, step])。 要跳过指定给定参数,可以使用None,以便例如a[start:]等同于a[slice(start, None)],或者a[::-1]等同于a[slice(None, None, -1)]

虽然基于:的表示法对于简单的切片非常有用,但是slice()对象的显式使用简化了切片的编程生成。

相关问题 更多 >