前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python中list的切片操作

Python中list的切片操作

作者头像
Tyan
发布2019-05-25 22:46:15
8640
发布2019-05-25 22:46:15
举报
文章被收录于专栏:SnailTyanSnailTyan

版权声明:博客文章都是作者辛苦整理的,转载请注明出处,谢谢! https://cloud.tencent.com/developer/article/1433818

文章作者:Tyan

博客:noahsnail.com | CSDN | 简书

1. list的切片操作

Python中可以对list使用索引来进行切片操作,其语法(Python3)如下:

代码语言:javascript
复制
a[:]           # a copy of the whole array
a[start:]      # items start through the rest of the array
a[:stop]       # items from the beginning through stop-1
a[start:stop]  # items start through stop-1

a[start:stop:step] # start through not past stop, by step

a[-1]    # last item in the array
a[-2:]   # last two items in the array
a[:-2]   # everything except the last two items


a[::-1]    # all items in the array, reversed
a[1::-1]   # the first two items, reversed
a[:-3:-1]  # the last two items, reversed
a[-3::-1]  # everything except the last two items, reversed

测试结果:

代码语言:javascript
复制
# 从0开始索引列表,索引值为整数
>>> a = list(range(10))  # 定义列表a
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a[:]  # 复制列表
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a[0:]  # 从索引为0的列表元素开始迭代列表至列表结束
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a[1:]  # 从索引为1的列表元素开始迭代列表至列表结束
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a[:9]  # 从索引为0的列表元素开始迭代列表至索引为8的列表元素,不包含索引为9的列表元素
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> a[3:5] # 从索引为3的列表元素开始迭代列表至索引为4的列表元素,不包含索引为5的列表元素
[3, 4]
>>> a[::1] # 从索引为0的列表元素开始索引列表,每次迭代索引值加1,直至列表结束
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a[::2] # 从索引为0的列表元素开始索引列表,每次迭代索引值加2,直至列表结束
[0, 2, 4, 6, 8]
>>> a[3:9:2] # 从索引为3的列表元素开始索引列表,每次迭代索引值加2,直至索引为8的列表元素,不包含索引为9的列表元素
[3, 5, 7]

# 当索引值为负数时
>>> a[-1] # 列表的最后一个元素
9
>>> a[-2:] # 从列表的倒数第二个元素直至列表结束,即从索引值为-2的元素直至列表结束
[8, 9]
>>> a[:-1] # 从列表的第一个元素直至列表的倒数第二个元素结束,不包含最后一个列表元素
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> a[:-2] # 从列表的第一个元素直至列表的倒数第三个元素结束,不包含最后两个个列表元素
[0, 1, 2, 3, 4, 5, 6, 7]


# 当step为负值时,表示逆向索引列表
>>> a[::-1] # 反转列表,从列表最后一个元素到列表的第一个元素
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>>> a[1::-1] # 从索引值为1的列表元素开始,逆向索引直列表开头
[1, 0]
>>> a[-3::-1] # 从索引值为-3的列表元素开始,逆向索引直列表开头
[7, 6, 5, 4, 3, 2, 1, 0]
>>> a[:-3:-1] # 从索引值为-1,逆向索引直索引为-2的元素结束,不包含索引为-3的元素
[9, 8]

参考资料

  1. https://stackoverflow.com/questions/509211/understanding-slice-notation
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019年04月29日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. list的切片操作
  • 参考资料
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档