列表切片list slicing

本文详细解释了Python中列表切片的语法及应用,包括如何使用[start:end:stride]来选择列表中的特定元素,并展示了如何通过列表切片反转整个列表。通过实例演示,帮助读者快速掌握这一高效操作技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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]

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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值