文件对象无法进行切片操作
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