标签:列表切片
切片取指定范围元素,指定开始、结束索引
>> a[1:3]
[2, 3]
只指定开始索引
>> a = ["a","b","c","d","e"]
>> a[0:]
[‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘]
只指定结束索引
>> a[:4]
[‘a‘, ‘b‘, ‘c‘, ‘d‘]
取列表副本,可以进行复制
>> a[:]
[‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘]>> a[-len(a)]#负数取第一元素
‘a‘
开始索引、结束索引都是负值
>> a[-5:-1] #两个都是负数时候,第一个值是小值,第二个元素是大值
[‘a‘, ‘b‘, ‘c‘, ‘d‘]
取倒数元素
取倒数第一个、倒数第二个元素
>> a = [0,1,2,3,4,5,6,7,8,9]
>> a[-1]
9
>> a[-2]
8
倒序输出元素
>> a = [0,1,2,3,4,5,6,7,8,9]
>> a[::-1] #切片实现倒序输出
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
倒序返回列表的后四个元素
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>> s[-1:-5:-1]
[9, 8, 7, 6]
输出列表末尾5个元素
>> a[-5:]
[5, 6, 7, 8, 9]
标签:列表切片
原文地址:http://blog.51cto.com/13496943/2126046