python 3-5 如何对迭代器做切片操作itertools.islice(open("test.txt"),0,10),迭代器消耗

来源:互联网 发布:炉石传说大数据2016 编辑:程序博客网 时间:2024/05/21 10:05

文件对象无法进行切片操作

islice用于切片操作islice(iterable, [start,] stop [, step]) --> islice objectislice(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,然后将其迭代器赋值给lailai赋值给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... 5678>>> for x in lai:...    print x... 910111213141516171819

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 0
原创粉丝点击