遇一山,过一山,处处有风景;只要勇敢向前,一路尽是繁花盛开。 | (点击查看→)【测试干货】python/java自动化、持续集成、性能、测开、简历、笔试面试等

python列表各种切片姿势

 顺着切,反着切,想怎么切就怎么切,但是别被坑。

mylist = [1,2,3,4,5,6,7,8,9]
print(mylist[2:7:2]) # [3, 5, 7]
print(mylist[:7:2]) # [1, 3, 5, 7]
print(mylist[2::2]) # [3, 5, 7, 9]
print(mylist[2:9:2]) # [3, 5, 7, 9]
print(mylist[2:10:2]) # [3, 5, 7, 9]
print(mylist[::2]) # [1, 3, 5, 7, 9]
print(mylist[7:2:2]) # []
print(mylist[2:7:-2]) # []
print(mylist[7:2:-2]) # [8, 6, 4]
print('============')
print(mylist[-2:-7:-2]) # [8, 6, 4]
print(mylist[:-7:-2]) # [9, 7, 5]
print(mylist[-2::-2]) # [8, 6, 4, 2]
print(mylist[-2:-10:-2]) # [8, 6, 4, 2]
print(mylist[::-2]) # [9, 7, 5, 3, 1]
print(mylist[-7:-2:-2]) # []
print(mylist[-2:-7:2]) # []
print(mylist[-7:-2:2]) # [3, 5, 7]

 

步长如果是整数,开始要小于结束,否则结果肯定为空
步长如果是负数,开始要大于结束,否则结果肯定为空 

 

# 反转
print(mylist[::-1]) # [9, 8, 7, 6, 5, 4, 3, 2, 1]
mylist.reverse()
print(mylist) # [9, 8, 7, 6, 5, 4, 3, 2, 1]

 

左闭右开

print([1,2,3,4,5,6,7,8,9][1:3:])  # [2, 3]
print([1,2,3,4,5,6,7,8,9][-1:-7:-1])  # [9, 8, 7, 6, 5, 4]

  

 

posted @ 2019-06-19 21:34  全栈测试笔记  阅读(1027)  评论(0编辑  收藏  举报
浏览器标题切换
浏览器标题切换end