python 切片索引语法

总结就是

变量[开始:结束:步长]

word = list(range(10))
print(list(word))
output:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
word[0]
output:0
word[5]
output:5
word[-1] #倒数第一个(由于 -0 和 0相同所以负索引从 -1 开始)
output:9
word[-2] #倒数第二个
output:8
word[-5] #倒数第五个(不能超出位置)
output:5

output:[0, 1]
word[2:100] #超出全部显示
output:[2, 3, 4, 5, 6, 7, 8, 9]

word[:2] #如果省略第一个索引那么就是从开头到第二个位置
output:[0, 1]
word[4:] #如果省略第二个索引那么就是从4到结尾
output:[4, 5, 6, 7, 8, 9]
word[-2:] #从倒数第二位(包括)到结尾
output:[8, 9]
word[::] #第一位和第二位索引都不写那么默认就是从头到尾
output:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

word[::2]
output:[0, 2, 4, 6, 8]
word[::3]
output:[0, 3, 6, 9]
word[::-1]
output:[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
word[::-2]
output:[9, 7, 5, 3, 1]
© 版权声明
THE END
喜欢就支持一下吧
点赞8赞赏 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容