python如何取一定范围的列表元素呢?
详情看示例1--3
直接看代码
1.分片
1 #取一定范围的元素2 lucky_number = [0,1,2,3,4,5,6]3 #分片4 print(lucky_number[1])5 print(lucky_number[-5:-1])6 print(lucky_number[0:7])
输出结果
1[2, 3, 4, 5][0, 1, 2, 3, 4, 5, 6]
2.捷径
1 #取一定范围的元素2 lucky_number = [0,1,2,3,4,5,6]3 #捷径4 print(lucky_number[-4:])5 print(lucky_number[-5:])
输出结果
[3, 4, 5, 6][2, 3, 4, 5, 6]
3.步长
1 #取一定范围的元素2 lucky_number = [0,1,2,3,4,5,6]3 #步长4 print(lucky_number[0:7:2])5 print(lucky_number[::2])6 print(lucky_number[::-2])
输出结果
[0, 2, 4, 6][0, 2, 4, 6][6, 4, 2, 0]