# Python切片示例代码
# 创建一个列表
my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# 获取列表的前三个元素
first_three = my_list[:3]
print("前三个元素:", first_three) # 输出: 前三个元素: [0, 1, 2]
# 获取列表的第4个到第7个元素(索引3到6)
middle_slice = my_list[3:7]
print("第4个到第7个元素:", middle_slice) # 输出: 第4个到第7个元素: [3, 4, 5, 6]
# 获取列表的最后三个元素
last_three = my_list[-3:]
print("最后三个元素:", last_three) # 输出: 最后三个元素: [7, 8, 9]
# 每隔两个元素取一个
every_other = my_list[::2]
print("每隔两个元素取一个:", every_other) # 输出: 每隔两个元素取一个: [0, 2, 4, 6, 8]
# 反转列表
reversed_list = my_list[::-1]
print("反转后的列表:", reversed_list) # 输出: 反转后的列表: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
list[start:stop:step],其中 start 是起始索引(包含),stop 是结束索引(不包含),step 是步长。start,则默认从列表的第一个元素开始;如果省略 stop,则默认到列表的最后一个元素结束。-1 表示最后一个元素。上一篇:python中str()的用法
下一篇:python正则表达
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站