列表切片list slicing

List slicing allows us to access elements of a list in a concise manner. The syntax looks like this:

[start:end:stride]

Where start describes where the slice starts (inclusive), end is where it ends (exclusive), and stride describes the space between items in the sliced list. For example, a stride of 2 would select every other item from the original list to place in the sliced list.

l = [i ** 2 for i in range(1, 11)]
# Should be [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
print l[2:9:2]

结果

[9, 25, 49, 81]
第一个参数为起始位置(包含),第二个为结束位置(不包含),第三个为跨度(每几个取一个)

反转list

my_list = range(1, 11)
backwards = my_list[::-1]
print backwards

结果

[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

跨度为负则会从最末往前取



在 Python 中,你可以使用切片(slicing)操作对列表进行切片。切片操作可以提取列表的子列表,以便你可以访问列表的特定部分。下面是一些关于切片操作的示例: ```python my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] # 提取从索引 1 到索引 4(不包括)的子列表 slice1 = my_list[1:4] print(slice1) # 输出: [2, 3, 4] # 提取从索引 2 开始到列表末尾的子列表 slice2 = my_list[2:] print(slice2) # 输出: [3, 4, 5, 6, 7, 8, 9] # 提取从列表开头到索引 5(不包括)的子列表 slice3 = my_list[:5] print(slice3) # 输出: [1, 2, 3, 4, 5] # 使用负数索引提取倒数第三个元素到倒数第一个元素的子列表 slice4 = my_list[-3:] print(slice4) # 输出: [7, 8, 9] # 使用步长提取每隔一个元素的子列表 slice5 = my_list[::2] print(slice5) # 输出: [1, 3, 5, 7, 9] ``` 在切片操作中,冒号(`:`)用于指定起始索引和结束索引。切片操作是左闭右开的,也就是说,开始索引包含在结果中,而结束索引不包含在结果中。 如果你省略起始索引,则默认从列表开头开始。如果你省略结束索引,则默认到列表末尾。 使用负数索引可以从列表的末尾开始计数。例如,`-1` 表示最后一个元素,`-2` 表示倒数第二个元素,依此类推。 你还可以使用步长来指定提取子列表时的间隔。例如,步长为 `2` 表示每隔一个元素提取一个元素。 希望这个示例对你有帮助!如果还有其他问题,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值