python高级特性:slice(切片)灵活指定范围-创新互联

在python 官网的解释:

成都创新互联为您提适合企业的网站设计 让您的网站在搜索引擎具有高度排名,让您的网站具备超强的网络竞争力!结合企业自身,进行网站设计及把握,最后结合企业文化和具体宗旨等,才能创作出一份性化解决方案。从网站策划到网站建设、做网站, 我们的网页设计师为您提供的解决方案。
  • classslice(stop)

  • classslice(start, stop[, step])

Return a slice object representing the set of indices specified by range(start, stop, step). The start and step arguments default to None. Slice objects have read-only data attributes start, stop and step which merely return the argument values (or their default). They have no other explicit functionality; however they are used by Numerical Python and other third party extensions. Slice objects are also generated when extended indexing syntax is used. For example: a[start:stop:step] or a[start:stop, i]. See itertools.islice() for an alternate version that returns an iterator.

一、普通指定范围方法

#将数字填入L

L = []; #list
n = 1;
while n <= 99:  
   L.insert(0, n);
   n = n + 1;
print L;

#take n in head
n = 10
for i in range(n):
   print i, ":", L[i];

python 高级特性:slice(切片) 灵活指定范围

二、slice方式

L = []; #list
n = 1;
while n <= 99:  
   L.insert(0, n);
   n = n + 1;

#slice
##follow way:

print "L[0:10]:", L[0:10]; #从第0位开始,第10位结束
print "L[:10]:", L[:10];   # = L[0:10]
print "L[::2]:", L[::2];    # = L[0:100:2] 逢2出1 
print "L[-2:]", L[-2:];    # 从左往右,倒数第二位开始
print "L[-2:-1]", L[-2:-1];  # 从左往右,倒数第二位开始 ,倒数第一位结束

print "L[:-90]:", L[:-90];

python 高级特性:slice(切片) 灵活指定范围print '';

string = 'abcdef'
print 'string:%s'%string;
print 'string[:3]:', string[:3];
print 'string[::2]:', string[::2];

python 高级特性:slice(切片) 灵活指定范围

可见,slice 比 循环还要简洁。

另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


标题名称:python高级特性:slice(切片)灵活指定范围-创新互联
标题URL:http://myzitong.com/article/djhcoj.html