Python的切片表示法是如何工作的?也就是说:当我编写[x:y:z]、a[:]、a]::2]等代码时,我如何理解哪些元素最终会出现在切片中?请在适当的地方附上参考资料。
另请参见:为什么切片和范围上限是互斥的?
Python的切片表示法是如何工作的?也就是说:当我编写[x:y:z]、a[:]、a]::2]等代码时,我如何理解哪些元素最终会出现在切片中?请在适当的地方附上参考资料。
另请参见:为什么切片和范围上限是互斥的?
当前回答
我个人认为这就像一个for循环:
a[start:end:step]
# for(i = start; i < end; i += step)
此外,请注意,start和end的负值是相对于列表末尾的,并且在上面的示例中通过given_index+a.shape[0]计算。
其他回答
您可以使用切片语法返回字符序列。
指定用冒号分隔的开始和结束索引,以返回字符串的一部分。
例子:
获取从位置2到位置5的字符(不包括):
b = "Hello, World!"
print(b[2:5])
从开始切片
通过省略起始索引,范围将从第一个字符开始:
例子:
获取从开始到位置5的字符(不包括):
b = "Hello, World!"
print(b[:5])
切片到底
通过省略结束索引,范围将结束:
例子:
从位置2获取字符,一直到结尾:
b = "Hello, World!"
print(b[2:])
负索引
使用负索引从字符串末尾开始切片:实例
获取字符:
来自:“世界!”中的“o”(位置-5)
至,但不包括:“世界!”中的“d”(位置-2):
b = "Hello, World!"
print(b[-5:-2])
已经有很多答案了,但我想添加一个性能比较
~$ python3.8 -m timeit -s 'fun = "this is fun;slicer = slice(0, 3)"' "fun_slice = fun[slicer]"
10000000 loops, best of 5: 29.8 nsec per loop
~$ python3.8 -m timeit -s 'fun = "this is fun"' "fun_slice = fun[0:3]"
10000000 loops, best of 5: 37.9 nsec per loop
~$ python3.8 -m timeit -s 'fun = "this is fun"' "fun_slice = fun[slice(0, 3)]"
5000000 loops, best of 5: 68.7 nsec per loop
~$ python3.8 -m timeit -s 'fun = "this is fun"' "slicer = slice(0, 3)"
5000000 loops, best of 5: 42.8 nsec per loop
因此,如果您重复使用同一个切片,使用切片对象将有益并提高可读性。然而,如果您只进行了几次切片,则应首选[:]表示法。
枚举序列x语法允许的可能性:
>>> x[:] # [x[0], x[1], ..., x[-1] ]
>>> x[low:] # [x[low], x[low+1], ..., x[-1] ]
>>> x[:high] # [x[0], x[1], ..., x[high-1]]
>>> x[low:high] # [x[low], x[low+1], ..., x[high-1]]
>>> x[::stride] # [x[0], x[stride], ..., x[-1] ]
>>> x[low::stride] # [x[low], x[low+stride], ..., x[-1] ]
>>> x[:high:stride] # [x[0], x[stride], ..., x[high-1]]
>>> x[low:high:stride] # [x[low], x[low+stride], ..., x[high-1]]
当然,如果(高低)%步幅!=0,则终点将略低于高1。
如果步幅为负,则由于我们正在倒计时,顺序会有点改变:
>>> x[::-stride] # [x[-1], x[-1-stride], ..., x[0] ]
>>> x[high::-stride] # [x[high], x[high-stride], ..., x[0] ]
>>> x[:low:-stride] # [x[-1], x[-1-stride], ..., x[low+1]]
>>> x[high:low:-stride] # [x[high], x[high-stride], ..., x[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)'
我个人认为这就像一个for循环:
a[start:end:step]
# for(i = start; i < end; i += step)
此外,请注意,start和end的负值是相对于列表末尾的,并且在上面的示例中通过given_index+a.shape[0]计算。
我想加一个你好,世界!为初学者解释切片基础知识的示例。这对我帮助很大。
让我们列出六个值[“P”、“Y”、“T”、“H”、“O”、“N”]:
+---+---+---+---+---+---+
| P | Y | T | H | O | N |
+---+---+---+---+---+---+
0 1 2 3 4 5
现在,该列表中最简单的部分是其子列表。符号是[<index>:<index>],关键是这样读:
[ start cutting before this index : end cutting before this index ]
现在,如果你从上面的列表中选择一个片段[2:5],就会发生这种情况:
| |
+---+---|---+---+---|---+
| P | Y | T | H | O | N |
+---+---|---+---+---|---+
0 1 | 2 3 4 | 5
在索引为2的元素之前进行了一次切割,在索引为5的元素之前又进行了一个切割。因此,结果将是这两个剪辑之间的一个片段,一个列表['T','H','O']。