博客
关于我
Python切片:[i:j]与[i:j:s]
阅读量:538 次
发布时间:2019-03-07

本文共 870 字,大约阅读时间需要 2 分钟。

Python 切片操作详解

第一部分:切片的基本用法

在 Python 中,a[i:j] 的含义是将从索引 ij-1 的元素复制一遍,生成一个新切片。切片的数据类型与被切片的对象完全一致。

示例:

>>> list1 = [1, 2, 3, 4, 5]>>> list1[1:4]  # 输出 [2, 3, 4]>>> tuple1 = ('a', 'b', 'c', 'd', 'e')>>> tuple1[1:4]  # 输出 ('b', 'c', 'd')>>> string1 = "abcde">>> string1[1:4]  # 输出 'bcd'

第二部分:默认值的使用

切片操作中,ij 的默认值非常实用:

  • i 未指定时,默认为 0
  • j 未指定时,默认为 len(a),即切片到末尾。
  • ij 均未指定时,a[:] 切片相当于复制整个列表 a

示例:

>>> list1 = [1, 2, 3, 4, 5]>>> list1[:3]  # 等同于 list1[0:3],输出 [1, 2, 3]>>> list1[3:]  # 等同于 list1[3:5],输出 [4, 5]>>> list1[:]  # 输出完整副本 [1, 2, 3, 4, 5]

第三部分:步长的使用

切片操作中,a[i:j:s]s 表示步长,默认值为 1,即每次只取一个元素。

关键点:

  • s < 0 时,ij 的默认值会发生变化:
    • i 未指定时,默认为 -1
    • j 未指定时,默认为 -(len(a) + 1)
  • a[::-1] 切片的含义是从最后一个元素开始,倒序切片到第一个元素。

示例:

>>> list1 = [1, 2, 3, 4, 5]>>> list1[::-1]  # 输出 [5, 4, 3, 2, 1]>>> list1[::-2]  # 步长为 -2,输出 [5, 3, 1]

这些切片操作为 Python 列表、元组和字符串提供了强大的灵活性,能够高效处理数据切片和重组任务。

转载地址:http://guknz.baihongyu.com/

你可能感兴趣的文章
Notepad++在线和离线安装JSON格式化插件
查看>>
notepad++最详情汇总
查看>>
notepad如何自动对齐_notepad++怎么自动排版
查看>>
Notes on Paul Irish's "Things I learned from the jQuery source" casts
查看>>
Notification 使用详解(很全
查看>>
NotImplementedError: Cannot copy out of meta tensor; no data! Please use torch.nn.Module.to_empty()
查看>>
Now trying to drop the old temporary tablespace, the session hangs.
查看>>
nowcoder—Beauty of Trees
查看>>
np.arange()和np.linspace()绘制logistic回归图像时得到不同的结果?
查看>>
np.power的使用
查看>>
NPM 2FA双重认证的设置方法
查看>>
npm build报错Cannot find module ‘webpack/lib/rules/BasicEffectRulePlugin‘解决方法
查看>>
npm build报错Cannot find module ‘webpack‘解决方法
查看>>
npm ERR! ERESOLVE could not resolve报错
查看>>
npm ERR! fatal: unable to connect to github.com:
查看>>
npm ERR! Unexpected end of JSON input while parsing near '...on":"0.10.3","direc to'
查看>>
npm ERR! Unexpected end of JSON input while parsing near ‘...“:“^1.2.0“,“vue-html-‘ npm ERR! A comp
查看>>
npm error Missing script: “server“npm errornpm error Did you mean this?npm error npm run serve
查看>>
npm error MSB3428: 未能加载 Visual C++ 组件“VCBuild.exe”。要解决此问题,1) 安装
查看>>
npm install CERT_HAS_EXPIRED解决方法
查看>>