Python的切片表示法是如何工作的?也就是说:当我编写[x:y:z]、a[:]、a]::2]等代码时,我如何理解哪些元素最终会出现在切片中?请在适当的地方附上参考资料。
另请参见:为什么切片和范围上限是互斥的?
Python的切片表示法是如何工作的?也就是说:当我编写[x:y:z]、a[:]、a]::2]等代码时,我如何理解哪些元素最终会出现在切片中?请在适当的地方附上参考资料。
另请参见:为什么切片和范围上限是互斥的?
当前回答
这是我教新手切片的方法:
理解索引和切片之间的区别:
WikiPython有一幅惊人的图片,它清楚地区分了索引和切片。
这是一个包含六个元素的列表。为了更好地理解切片,请将该列表视为一组放在一起的六个框。每个盒子里都有一个字母表。
索引就像处理盒子的内容。您可以检查任何框的内容。但是你不能同时检查多个盒子的内容。你甚至可以替换盒子里的东西。但你不能在一个盒子里放两个球,也不能一次换两个球。
In [122]: alpha = ['a', 'b', 'c', 'd', 'e', 'f']
In [123]: alpha
Out[123]: ['a', 'b', 'c', 'd', 'e', 'f']
In [124]: alpha[0]
Out[124]: 'a'
In [127]: alpha[0] = 'A'
In [128]: alpha
Out[128]: ['A', 'b', 'c', 'd', 'e', 'f']
In [129]: alpha[0,1]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-129-c7eb16585371> in <module>()
----> 1 alpha[0,1]
TypeError: list indices must be integers, not tuple
切片就像处理盒子一样。你可以拿起第一个盒子放在另一张桌子上。要拿起盒子,你只需要知道盒子的开始和结束位置。
您甚至可以选择前三个框或最后两个框,或1到4之间的所有框。所以,如果你知道开始和结束,你可以选择任何一组框。这些位置称为开始和停止位置。
有趣的是,您可以同时替换多个框。此外,您可以在任何地方放置多个盒子。
In [130]: alpha[0:1]
Out[130]: ['A']
In [131]: alpha[0:1] = 'a'
In [132]: alpha
Out[132]: ['a', 'b', 'c', 'd', 'e', 'f']
In [133]: alpha[0:2] = ['A', 'B']
In [134]: alpha
Out[134]: ['A', 'B', 'c', 'd', 'e', 'f']
In [135]: alpha[2:2] = ['x', 'xx']
In [136]: alpha
Out[136]: ['A', 'B', 'x', 'xx', 'c', 'd', 'e', 'f']
切片步骤:
到目前为止,您已连续拾取箱子。但有时你需要单独拾取。例如,您可以每隔一秒钟拾取一个盒子。你甚至可以从最后每隔三个盒子取一个。该值称为步长。这代表了您连续拾取之间的差距。如果您从开始到结束拾取框,则步长应为正值,反之亦然。
In [137]: alpha = ['a', 'b', 'c', 'd', 'e', 'f']
In [142]: alpha[1:5:2]
Out[142]: ['b', 'd']
In [143]: alpha[-1:-5:-2]
Out[143]: ['f', 'd']
In [144]: alpha[1:5:-2]
Out[144]: []
In [145]: alpha[-1:-5:2]
Out[145]: []
Python如何找出缺少的参数:
切片时,如果忽略了任何参数,Python会尝试自动计算。
如果您检查CPython的源代码,您会发现一个名为PySlice_GetIndices Ex()的函数,它计算出任何给定参数的切片索引。下面是Python中的逻辑等价代码。
此函数采用Python对象和可选参数进行切片,并返回所请求切片的开始、停止、步骤和切片长度。
def py_slice_get_indices_ex(obj, start=None, stop=None, step=None):
length = len(obj)
if step is None:
step = 1
if step == 0:
raise Exception("Step cannot be zero.")
if start is None:
start = 0 if step > 0 else length - 1
else:
if start < 0:
start += length
if start < 0:
start = 0 if step > 0 else -1
if start >= length:
start = length if step > 0 else length - 1
if stop is None:
stop = length if step > 0 else -1
else:
if stop < 0:
stop += length
if stop < 0:
stop = 0 if step > 0 else -1
if stop >= length:
stop = length if step > 0 else length - 1
if (step < 0 and stop >= start) or (step > 0 and start >= stop):
slice_length = 0
elif step < 0:
slice_length = (stop - start + 1)/(step) + 1
else:
slice_length = (stop - start - 1)/(step) + 1
return (start, stop, step, slice_length)
这就是切片背后的智慧。由于Python有一个名为slice的内置函数,您可以传递一些参数,并检查它如何巧妙地计算缺少的参数。
In [21]: alpha = ['a', 'b', 'c', 'd', 'e', 'f']
In [22]: s = slice(None, None, None)
In [23]: s
Out[23]: slice(None, None, None)
In [24]: s.indices(len(alpha))
Out[24]: (0, 6, 1)
In [25]: range(*s.indices(len(alpha)))
Out[25]: [0, 1, 2, 3, 4, 5]
In [26]: s = slice(None, None, -1)
In [27]: range(*s.indices(len(alpha)))
Out[27]: [5, 4, 3, 2, 1, 0]
In [28]: s = slice(None, 3, -1)
In [29]: range(*s.indices(len(alpha)))
Out[29]: [5, 4]
注:这篇文章最初写在我的博客《Python切片背后的智能》中。
其他回答
上面的答案不讨论切片分配。为了理解切片分配,可以在ASCII艺术中添加另一个概念:
+---+---+---+---+---+---+
| P | y | t | h | o | n |
+---+---+---+---+---+---+
Slice position: 0 1 2 3 4 5 6
Index position: 0 1 2 3 4 5
>>> p = ['P','y','t','h','o','n']
# Why the two sets of numbers:
# indexing gives items, not lists
>>> p[0]
'P'
>>> p[5]
'n'
# Slicing gives lists
>>> p[0:1]
['P']
>>> p[0:2]
['P','y']
一种启发式方法是,对于从零到n的切片,思考:“零是开始,从开始开始,在列表中取n个项目”。
>>> p[5] # the last of six items, indexed from zero
'n'
>>> p[0:5] # does NOT include the last item!
['P','y','t','h','o']
>>> p[0:6] # not p[0:5]!!!
['P','y','t','h','o','n']
另一种启发式方法是,“对于任何一个切片,用零替换开头,应用前面的启发式方法获得列表的结尾,然后将第一个数字向后计数,以从开头删除项目”
>>> p[0:4] # Start at the beginning and count out 4 items
['P','y','t','h']
>>> p[1:4] # Take one item off the front
['y','t','h']
>>> p[2:4] # Take two items off the front
['t','h']
# etc.
切片分配的第一个规则是,由于切片返回一个列表,所以切片分配需要一个列表(或其他可迭代的):
>>> p[2:3]
['t']
>>> p[2:3] = ['T']
>>> p
['P','y','T','h','o','n']
>>> p[2:3] = 't'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only assign an iterable
切片分配的第二个规则(您也可以在上面看到)是,无论切片索引返回列表的哪个部分,都是由切片分配更改的相同部分:
>>> p[2:4]
['T','h']
>>> p[2:4] = ['t','r']
>>> p
['P','y','t','r','o','n']
切片分配的第三条规则是,分配的列表(可迭代)不必具有相同的长度;索引切片被简单地切片,并被分配的任何内容整体替换:
>>> p = ['P','y','t','h','o','n'] # Start over
>>> p[2:4] = ['s','p','a','m']
>>> p
['P','y','s','p','a','m','o','n']
最难习惯的部分是分配给空切片。使用启发式1和2,很容易让你的头脑围绕空切片进行索引:
>>> p = ['P','y','t','h','o','n']
>>> p[0:4]
['P','y','t','h']
>>> p[1:4]
['y','t','h']
>>> p[2:4]
['t','h']
>>> p[3:4]
['h']
>>> p[4:4]
[]
然后,一旦您看到了这一点,将切片分配给空切片也是有意义的:
>>> p = ['P','y','t','h','o','n']
>>> p[2:4] = ['x','y'] # Assigned list is same length as slice
>>> p
['P','y','x','y','o','n'] # Result is same length
>>> p = ['P','y','t','h','o','n']
>>> p[3:4] = ['x','y'] # Assigned list is longer than slice
>>> p
['P','y','t','x','y','o','n'] # The result is longer
>>> p = ['P','y','t','h','o','n']
>>> p[4:4] = ['x','y']
>>> p
['P','y','t','h','x','y','o','n'] # The result is longer still
请注意,因为我们没有更改切片的第二个编号(4),所以插入的项目总是紧靠“o”堆叠,即使我们分配给空切片也是如此。因此,空切片分配的位置是非空切片分配位置的逻辑扩展。
稍微后退一点,当你继续进行我们的切片开始计数过程时会发生什么?
>>> p = ['P','y','t','h','o','n']
>>> p[0:4]
['P','y','t','h']
>>> p[1:4]
['y','t','h']
>>> p[2:4]
['t','h']
>>> p[3:4]
['h']
>>> p[4:4]
[]
>>> p[5:4]
[]
>>> p[6:4]
[]
通过切片,一旦你完成,你就完成了;它不会开始向后倾斜。在Python中,除非使用负数明确要求,否则不会获得负的步幅。
>>> p[5:3:-1]
['n','o']
“一旦你完成了,你就完成了”规则会产生一些奇怪的后果:
>>> p[4:4]
[]
>>> p[5:4]
[]
>>> p[6:4]
[]
>>> p[6]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
事实上,与索引相比,Python切片具有奇怪的防错误性:
>>> p[100:200]
[]
>>> p[int(2e99):int(1e99)]
[]
这有时会派上用场,但也会导致一些奇怪的行为:
>>> p
['P', 'y', 't', 'h', 'o', 'n']
>>> p[int(2e99):int(1e99)] = ['p','o','w','e','r']
>>> p
['P', 'y', 't', 'h', 'o', 'n', 'p', 'o', 'w', 'e', 'r']
根据您的应用程序,这可能。。。或者可能不。。。成为你在那里所希望的!
以下是我的原始答案。它对很多人都很有用,所以我不想删除它。
>>> r=[1,2,3,4]
>>> r[1:1]
[]
>>> r[1:1]=[9,8]
>>> r
[1, 9, 8, 2, 3, 4]
>>> r[1:1]=['blah']
>>> r
[1, 'blah', 9, 8, 2, 3, 4]
这也可以澄清切片和索引之间的区别。
我个人认为这就像一个for循环:
a[start:end:step]
# for(i = start; i < end; i += step)
此外,请注意,start和end的负值是相对于列表末尾的,并且在上面的示例中通过given_index+a.shape[0]计算。
语法为:
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
还有一个步长值,可用于上述任何一项:
a[start:stop:step] # start through not past stop, by step
要记住的关键点是:stop值表示不在所选切片中的第一个值。因此,停止和开始之间的区别是所选元素的数量(如果步骤为1,则为默认值)。
另一个特点是start或stop可以是负数,这意味着它从数组的末尾开始计数,而不是从开始计数。因此:
a[-1] # last item in the array
a[-2:] # last two items in the array
a[:-2] # everything except the last two items
类似地,步骤可以是负数:
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对程序员很友好。例如,如果您请求一个[:-2],而一个只包含一个元素,则会得到一个空列表而不是一个错误。有时你会更喜欢错误,所以你必须意识到这可能会发生。
与切片对象的关系
切片对象可以表示切片操作,即:
a[start:stop:step]
相当于:
a[slice(start, stop, step)]
根据参数的数量,切片对象的行为也略有不同,类似于range(),即切片(stop)和切片(start,stop[,step])都受支持。要跳过指定给定参数,可以使用None,例如[start:]等同于[sslice(start,None)]或[::-1]等同于[Sslice(None,None,-1)]。
虽然基于:的表示法对简单切片非常有用,但slice()对象的显式使用简化了切片的编程生成。
在Python中,最基本的切片形式如下:
l[start:end]
其中l是一些集合,start是一个包含索引,end是一个独占索引。
In [1]: l = list(range(10))
In [2]: l[:5] # First five elements
Out[2]: [0, 1, 2, 3, 4]
In [3]: l[-5:] # Last five elements
Out[3]: [5, 6, 7, 8, 9]
当从开始切片时,可以省略零索引,而当切片到结束时,可以忽略最终索引,因为它是冗余的,所以不要冗长:
In [5]: l[:3] == l[0:3]
Out[5]: True
In [6]: l[7:] == l[7:len(l)]
Out[6]: True
负整数在相对于集合结尾进行偏移时非常有用:
In [7]: l[:-1] # Include all elements but the last one
Out[7]: [0, 1, 2, 3, 4, 5, 6, 7, 8]
In [8]: l[-3:] # Take the last three elements
Out[8]: [7, 8, 9]
切片时可以提供超出范围的索引,例如:
In [9]: l[:20] # 20 is out of index bounds, and l[20] will raise an IndexError exception
Out[9]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [11]: l[-20:] # -20 is out of index bounds, and l[-20] will raise an IndexError exception
Out[11]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
请记住,分割集合的结果是一个全新的集合。此外,当在赋值中使用切片表示法时,切片赋值的长度不需要相同。将保留分配切片之前和之后的值,集合将收缩或增长以包含新值:
In [16]: l[2:6] = list('abc') # Assigning fewer elements than the ones contained in the sliced collection l[2:6]
In [17]: l
Out[17]: [0, 1, 'a', 'b', 'c', 6, 7, 8, 9]
In [18]: l[2:5] = list('hello') # Assigning more elements than the ones contained in the sliced collection l [2:5]
In [19]: l
Out[19]: [0, 1, 'h', 'e', 'l', 'l', 'o', 6, 7, 8, 9]
如果忽略开始索引和结束索引,则将创建集合的副本:
In [14]: l_copy = l[:]
In [15]: l == l_copy and l is not l_copy
Out[15]: True
如果在执行赋值操作时省略了开始和结束索引,则集合的整个内容将替换为引用内容的副本:
In [20]: l[:] = list('hello...')
In [21]: l
Out[21]: ['h', 'e', 'l', 'l', 'o', '.', '.', '.']
除了基本切片外,还可以应用以下符号:
l[start:end:step]
其中l是一个集合,start是一个包含索引,end是一个排他索引,step是一个步长,可以用来获取l中的每n个项目。
In [22]: l = list(range(10))
In [23]: l[::2] # Take the elements which indexes are even
Out[23]: [0, 2, 4, 6, 8]
In [24]: l[1::2] # Take the elements which indexes are odd
Out[24]: [1, 3, 5, 7, 9]
使用step提供了在Python中反转集合的有用技巧:
In [25]: l[::-1]
Out[25]: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
也可以使用负整数作为步骤,如下例所示:
In[28]: l[::-2]
Out[28]: [9, 7, 5, 3, 1]
然而,使用负值作为步长可能会变得非常混乱。此外,为了成为Pythonic,您应该避免在单个切片中使用start、end和step。如果需要这样做,可以考虑在两个任务中完成(一个任务是切片,另一个任务则是跨步)。
In [29]: l = l[::2] # This step is for striding
In [30]: l
Out[30]: [0, 2, 4, 6, 8]
In [31]: l = l[1:-1] # This step is for slicing
In [32]: l
Out[32]: [2, 4, 6]
简单易懂:
在Python中,切片符号a[start:stop:step]可以用于从序列中选择一系列元素(例如列表、元组或字符串)。
起始索引是包括在切片中的第一个元素,
停止索引是从切片中排除的第一个元素,也是最后一个元素
步长值是切片元素之间的索引数。
例如,考虑以下列表:
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
如果要选择a的所有元素,可以使用切片符号a[:]:
>>> a[:]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
如果我们想选择a的所有元素,但跳过其他元素,我们可以使用切片符号a[::2]:
>>> a[::2]
[0, 2, 4, 6, 8]
如果我们想选择从第三个元素(索引2)到第七个元素(索引号6)的所有元素,我们可以使用切片符号a[2:7]:
>>> a[2:7]
[2, 3, 4, 5, 6]
如果我们想选择从第三个元素(索引2)到第七个元素(索引号6)的所有元素,但跳过其他元素,我们可以使用切片符号a[2:7:2]:
>>> a[2:7:2]
[2, 4, 6]
如果我们想选择从第三个元素(索引2)到列表末尾的所有元素,我们可以使用切片符号a[2:]:
>>> a[2:]
[2, 3, 4, 5, 6, 7, 8, 9]
如果我们想选择从列表开头到第七个元素(索引6)的所有元素,我们可以使用切片符号a[:7]:
>>> a[:7]
[0, 1, 2, 3, 4, 5, 6]
如果您想了解有关切片表示法的更多信息,可以参考Python官方文档:链接1链接2