python切片原理
2021/6/11 22:24:16
本文主要是介绍python切片原理,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
#slice has three params[start,stop,step] ''' if step = 0: return error elif step > 0: if start is on the left of the stop,: return [start,start+step,...,until stop,not include stop] if start is on the right of the stop,including start = stop: return [] else step < 0: if start is on the right of the stop,: return [start,start+step,...,until stop,not include stop] if start is on the left of the stop,including start = stop: return [] the fault value of step is 1 if the start and stop are unkown, then start and stop is depend on +/- of step index could be -infinite to +infinite, but only -len(list) to len(list)-1 maps to value others map to NONE for index >= len(list), we consider it is on the right of the list's end, maps to NONE for index < -len(list), we consider it is on the left of the list's start, maps to NONE for a five-numbers list,that is: ... -7 -6 -5 -4 -3 -2 -1 NONE NONE 0 1 2 3 4 5 6 7 <-----list-----> e.g. but we consider -7 is at the left of -5 ''' list0 = [i for i in range(10)] ''' [ 0 1 2 3 4 5 6 7 8 9] 0 1 2 3 4 5 6 7 8 9 10 11 ... +index ... -12 -11 -10-9 -8 -7 -6 -5 -4 -3 -2 -1 -index ''' list1 = list0[1:5] list2 = list0[1:-1] list3 = list0[-8:6] list4 = list0[-1:-5:-2] list5 = list0[15::-1]# stop <= -11 list6 = list0[-11:11] list7 = list0[-13:]#stop >=10 list8 = list0[10:] print('list1',list1) print('list2',list2) print('list3',list3) print('list4',list4) print('list5',list5) print('list6',list6) print('list7',list7) print('list8',list8) ''' results: list1 [1, 2, 3, 4] list2 [1, 2, 3, 4, 5, 6, 7, 8] list3 [2, 3, 4, 5] list4 [9, 7] list5 [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] list6 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] list7 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] list8 [] '''
这篇关于python切片原理的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-25Python编程基础:变量与类型
- 2024-11-25Python编程基础与实践
- 2024-11-24Python编程基础详解
- 2024-11-21Python编程基础教程
- 2024-11-20Python编程基础与实践
- 2024-11-20Python编程基础与高级应用
- 2024-11-19Python 基础编程教程
- 2024-11-19Python基础入门教程
- 2024-11-17在FastAPI项目中添加一个生产级别的数据库——本地环境搭建指南
- 2024-11-16`PyMuPDF4LLM`:提取PDF数据的神器