1、空切片分配的位置是非空切片分配位置的逻辑扩展。
>>> 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' 对齐,即使我们分配给空切片也是如此。
2、切片一旦完成,它不会开始向后切片。在 Python中,除非使用负数明确要求它们,否则不会得到负步幅。
>>> p[5:3:-1] ['n','o']
3、与索引相比,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']
以上就是python切片功能的使用,希望对大家有所帮助。更多Python学习指路:
本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。