selfteaching / selfteaching/selfteaching-python-camp

Day05 Python中的切片问题

Open
#154 0 comments 4 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

学习素材分享
Dominant language
Python
Stars
151
Forks
875
PR merge metrics
No merged PRs in 30d

Description

由于今天的资料中有关切片的部分刚开始没有看懂,后续在查找了相关的书籍和资料,终于弄明白了,现将自己的理解分享给大家:
1、切片对象的索引方式
索引方式分为正索引和负索引,以列表message为例:message=[a,b,c,d,e,f,g,h,i,j]
值: a b c d e f g h i j
正: 0 1 2 3 4 5 6 7 8 9
负:-10 -9 -8 -7 -6 -5 -4 -3 -2 -1
在Python中,第一个列表元素的索引为0,而不是1,Python为访问最后一个列表元素提供了一种特殊的语法,通过索引指定为-1,可以让Python返回最后一个列表元素。
2、切片的方式
切片操作基本表达式:object[start_index:end_index:step]
表达式包含两个“:”,用于分隔三个参数(start_index、end_index、step),当只有一个“:”时,默认第三个参数step=1。
start_index:表示起始索引(包含该索引本身)
end_index:表示终止索引(不包含该索引本身)
step:可以是正数,也可以为负数,其绝对值大小决定了切取数据时的‘‘步长”,正数表示“从左往右”取值,负表示“从右往左”取值。当step省略时,默认为1,即从左往右以增量1取值。
3、举例说明python切片

(1)切取单个值
>>>message[0]
>>>a
>>>message[-6]
>>>e
(2)切取所有值
>>>message[:] #从左往右
>>> [a,b,c,d,e,f,g,h,i,j]
>>>message[::]#从左往右
>>> [a,b,c,d,e,f,g,h,i,j]
>>>message[::-1]#从右往左
>>> [j, i, h, g, f, e, d, c, b, a]
(3)正索引
>>>message[1:5]
>>> [b,c,d,e]
step=1,从左往右取值,start_index=1到end_index=5同样表示从左往右取值。

>>>message[:7]
>>> [a,b,c,d,e,f,g]
step=1,从左往右取值,从“起点”开始一直取到end_index=6。
(4)负索引
>>>message[-1:-6:-1]
>>> [j, i, h, g, f]
step=-1,从右往左取值,start_index=-1到end_index=-6同样是从右往左取值。

>>>message[-1:-6]
>>> []
step=1,从左往右取值,而start_index=-1到end_index=-6决定了从右往左取值,两者矛盾,所以为空。
(5)正负混合索引
>>>message[1:-6]
>>> [b, c, d]
start_index=1在end_index=-6的左边,因此从左往右取值,而step=1同样决定了从左往右取值.

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reviewing the Python slicing explanation and examples in the issue body. No repository file, test, or documentation entry point is named, so first clarify where this material belongs and whether it should be added or corrected. Done means the intended documentation location is identified and the slicing examples are accurate.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
documentation
Issue type
Documentation
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.