Python的切片表示法是如何工作的?也就是说:当我编写[x:y:z]、a[:]、a]::2]等代码时,我如何理解哪些元素最终会出现在切片中?请在适当的地方附上参考资料。
另请参见:为什么切片和范围上限是互斥的?
Python的切片表示法是如何工作的?也就是说:当我编写[x:y:z]、a[:]、a]::2]等代码时,我如何理解哪些元素最终会出现在切片中?请在适当的地方附上参考资料。
另请参见:为什么切片和范围上限是互斥的?
当前回答
Python教程对此进行了讨论(向下滚动一点,直到您了解到关于切片的部分)。
ASCII艺术图也有助于记住切片的工作方式:
+---+---+---+---+---+---+
| P | y | t | h | o | n |
+---+---+---+---+---+---+
0 1 2 3 4 5 6
-6 -5 -4 -3 -2 -1
记住切片工作方式的一种方法是将索引视为字符之间的指针,第一个字符的左边缘编号为0。然后,n个字符串的最后一个字符的右边缘具有索引n。
其他回答
在找到这张很棒的桌子http://wiki.python.org/moin/MovingToPythonFromOtherLanguages
Python indexes and slices for a six-element list.
Indexes enumerate the elements, slices enumerate the spaces between the elements.
Index from rear: -6 -5 -4 -3 -2 -1 a=[0,1,2,3,4,5] a[1:]==[1,2,3,4,5]
Index from front: 0 1 2 3 4 5 len(a)==6 a[:5]==[0,1,2,3,4]
+---+---+---+---+---+---+ a[0]==0 a[:-2]==[0,1,2,3]
| a | b | c | d | e | f | a[5]==5 a[1:2]==[1]
+---+---+---+---+---+---+ a[-1]==5 a[1:-1]==[1,2,3,4]
Slice from front: : 1 2 3 4 5 : a[-2]==4
Slice from rear: : -5 -4 -3 -2 -1 :
b=a[:]
b==[0,1,2,3,4,5] (shallow copy of a)
当我第一次看到切片语法时,有一些事情不是很明显:
>>> x = [1,2,3,4,5,6]
>>> x[::-1]
[6,5,4,3,2,1]
反转顺序的简单方法!
如果出于某种原因,您希望以相反的顺序进行每一项:
>>> x = [1,2,3,4,5,6]
>>> x[::-2]
[6,4,2]
我有点沮丧,因为找不到一个准确描述切片功能的在线源代码或Python文档。
我接受了Aaron Hall的建议,阅读了CPython源代码的相关部分,并编写了一些Python代码,这些代码执行切片与CPython中的切片类似。我已经用Python 3对整数列表进行了数百万次随机测试。
您可能会发现我的代码中对CPython中相关函数的引用很有用。
def slicer(x, start=None, stop=None, step=None):
""" Return the result of slicing list x.
See the part of list_subscript() in listobject.c that pertains
to when the indexing item is a PySliceObject.
"""
# Handle slicing index values of None, and a step value of 0.
# See PySlice_Unpack() in sliceobject.c, which
# extracts start, stop, step from a PySliceObject.
maxint = 10000000 # A hack to simulate PY_SSIZE_T_MAX
if step is None:
step = 1
elif step == 0:
raise ValueError('slice step cannot be zero')
if start is None:
start = maxint if step < 0 else 0
if stop is None:
stop = -maxint if step < 0 else maxint
# Handle negative slice indexes and bad slice indexes.
# Compute number of elements in the slice as slice_length.
# See PySlice_AdjustIndices() in sliceobject.c
length = len(x)
slice_length = 0
if start < 0:
start += length
if start < 0:
start = -1 if step < 0 else 0
elif start >= length:
start = length - 1 if step < 0 else length
if stop < 0:
stop += length
if stop < 0:
stop = -1 if step < 0 else 0
elif stop > length:
stop = length - 1 if step < 0 else length
if step < 0:
if stop < start:
slice_length = (start - stop - 1) // (-step) + 1
else:
if start < stop:
slice_length = (stop - start - 1) // step + 1
# Cases of step = 1 and step != 1 are treated separately
if slice_length <= 0:
return []
elif step == 1:
# See list_slice() in listobject.c
result = []
for i in range(stop - start):
result.append(x[i+start])
return result
else:
result = []
cur = start
for i in range(slice_length):
result.append(x[cur])
cur += step
return result
我个人认为这就像一个for循环:
a[start:end:step]
# for(i = start; i < end; i += step)
此外,请注意,start和end的负值是相对于列表末尾的,并且在上面的示例中通过given_index+a.shape[0]计算。
简单易懂:
在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