总结:Python列表的切片

列表使用:切片

切片操作基本表达式:[start_index:stop_index:step] start 值:
(1)start_index,如果没有指定,则默认开始值为 0;
(2)stop_index 值: 指示到哪个索引值结束,但不包括这个结束索引值。如果没有指定,则取列表允许的最大索引值(即list.length);
(3)step 值: 步长值指示每一步大小,如果没有指定,则默认步长值为 1。
(4)当 step>0,start_index 的空值下标为 0,stop_index 为空时,值下标为list.length,step 的方向是左到右;
(5)当 step<0,start_index 的空值下标为list.length,stop_index 的空值下标为 0,此时反向为右到左
三个值都是可选的,非必填

访问列表中的值

使用下标索引来访问列表中的值,同样你也可以使用方括号的形式截取字符

索引

默认正向索引,编号从 0 开始。
支持反向索引,编号从-1 开始。

列表切片示意图:

索引包括正索引和负索引两部分,如上图所示,以list对象list = [“red”,“green”,“blue”,“yellow”,“white”,“black”]为例:

1. 获取单个元素

list = ["red","green","blue","yellow","white","black"]
#red
print(list[0])
# black
print(list[-1])

可以通过列表的索引获取列表的值

2.获取列表对象

list = ["red","green","blue","yellow","white","black"]
'''
从左往右获取索引,['red', 'green', 'blue', 'yellow', 'white', 'black']
'''
print(list[:])
print(list[::])
print(list[::1])
'''
从右往左获取索引(反向索引),['black', 'white', 'yellow', 'blue', 'green', 'red']
'''
print(list[::-1])

3.获取列表部分的值

列表切片遵循的是前闭后开原则(意思是最后一个索引对应的值是获取不到)

(1)正向索引

'''
list = ["red","green","blue","yellow","white","black"]
"""
正向索引:step为正数
"""
# 正向索引:start_index为0到end_index为6
print(list[0:6]) # ['red', 'green', 'blue', 'yellow', 'white', 'black']

# start_index没有填写,默认从第一个开始,一直取到end_index=6
print(list[:6]) # ['red', 'green', 'blue', 'yellow', 'white', 'black']

# step没有填写,默认是1,start_index为0,一直取到end_index=2
print(list[0:2])  #['red', 'green']

# step没有填写,默认是1,start_index为1,一直取到end_index=4
print(list[1:4])  # ['green', 'blue', 'yellow']

# start_index为1,一直取到end_index=5,step是2
print(list[1:5:2])  # ['green', 'yellow']

(2)反向索引

'''
反向索引:step为负数
'''
print("反向索引=============")
# step=1,反向索引,从start_index=-6开始,一直取到end_index=0为止。
print(list[-6::])  #['red', 'green', 'blue', 'yellow', 'white', 'black']

# step=-1,反向索引,从start_index=3开始,一直取到end_index=0为止。
print(list[3:0:-1])  #['yellow', 'blue', 'green']

# step=-2,反向索引,从start_index=6开始,一直取到end_index=0为止。
print(list[6::-2])  #['black', 'yellow', 'green']

# step=-3,反向索引,从start_index=5开始,一直取到end_index=2为止。
print(list[5:2:-3])  #['black']

# step=-1,反向索引,从start_index=-3开始,一直取到end_index=-5为止。
print(list[-3:-5:-1])  #['yellow', 'blue']

# start_index > end_index时,取出的结果为空
print(list[4:2])  #[]
print(list[-5:-3:-1])  # []

4、列表多层切片

'''多层切片'''
list = ["red","green","blue","yellow","white","black"]
# 链式列表切片
print(list[:6][2:5][-1:])

'''上边的链式列表与下边的步骤是相等的'''
list2 = list[:6]
# ['red', 'green', 'blue', 'yellow', 'white', 'black']
print(list2)
list3 = list2[2:5]
# ['blue', 'yellow', 'white']
print(list3)
list4 = list3[-1:]
# ['white']
print(list4)

来源:橙子软件测试菇凉

物联沃分享整理
物联沃-IOTWORD物联网 » 总结:Python列表的切片

发表评论