列表切片list slicing

来源:互联网 发布:数据恢复 破解版 编辑:程序博客网 时间:2024/05/12 00:37

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]

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



0 0
原创粉丝点击