Python中的分片

版权声明:本文原创,未经许可严禁转载。QQ群:QT&C/C++爱好者271251545 https://blog.csdn.net/xuancailinggan/article/details/52028873

Python中的分片对于提取数据非常有用。

分片的时候支持三个参数:起始索引、终止索引和步长

 
 
num=[1,2,3,4,5,6,7,8,9,10]
print(num[0:5])
print(num[0:8:2])
print(num[10:0:-1])

输出结果:
[1, 2, 3, 4, 5]
[1, 3, 5, 7]
[10, 9, 8, 7, 6, 5, 4, 3, 2]
从代码可以看出以下几点:
一、步长是可以省略的
二、正序的索引是前小后大,倒序的索引是前大后小,而且步长是负数。
当然你也可以省略首尾的索引,尝试如下的代码:
 
 
print(num[:8:2])
<pre style="background-color:#ffffff;color:#000000;font-family:'宋体';font-size:13.5pt;"><pre name="code" class="plain">print(num[0::2])
<pre style="background-color:#ffffff;color:#000000;font-family:'宋体';font-size:13.5pt;"><pre name="code" class="plain">print(num[::2])
输出结果也是非常有意思的。

 
 
 
 
 
 
 
 

猜你喜欢

转载自blog.csdn.net/xuancailinggan/article/details/52028873