python 3-5 如何对迭代器做切片操作

文件对象切片操作

islice用于切片操作
islice(iterable, [start,] stop [, step]) --> islice object
islice(f,0,10) 取文件的前10行
islice(f,100,300) #生成 文件 100 到  300 行的生成器,不包含第300行
islice(f,500) #生成500行以内的生成器
islice(f,500,None) #生成500行以后的生成器
for line in islice(f,0,10):
    print line

迭代器消耗

首先la 通过列表解析生成一个list,然后将其迭代器赋值给lai
lai赋值给islice后消耗掉前9个index,islice之后再次遍历lai时候,会从index=10开始迭代

la = [x for x in xrange(20)]
>>> lai = iter(la)
>>> for item in islice(lai,5,9):
...    print item
... 
5
6
7
8
>>> for x in lai:
...    print x
... 
9
10
11
12
13
14
15
16
17
18
19

islice帮助信息

islice实现了iter 和 next()表明islice既是可迭代对象又是迭代器

>>> help(islice)
Help on class islice in module itertools:

class islice(__builtin__.object)
 |  islice(iterable, [start,] stop [, step]) --> islice object
 |  
 |  Return an iterator whose next() method returns selected values from an
 |  iterable.  If start is specified, will skip all preceding elements;
 |  otherwise, start defaults to zero.  Step defaults to one.  If
 |  specified as another value, step determines how many values are 
 |  skipped between successive calls.  Works like a slice() on a list
 |  but returns an iterator.
 |  
 |  Methods defined here:
 |  
 |  __getattribute__(...)
 |      x.__getattribute__('name') <==> x.name
 |  
 |  __iter__(...)
 |      x.__iter__() <==> iter(x)
 |  
 |  next(...)
 |      x.next() -> the next value, or raise StopIteration
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  __new__ = <built-in method __new__ of type object>
 |      T.__new__(S, ...) -> a new object with type S, a subtype of T
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值