>>> def count(n):
... while True:
... yield n
... n += 1
...
>>> c = count(0)
>>> c[10:20]
Traceback (most recent call last):
File "", line 1, in
TypeError: 'generator' object has no attribute '__getitem__' >>> for x in itertools.islice(c, 10, 20):
... print x
...
10
11
12
13
14
15
16
17
18
19
islice() will consume data on the iterator. Iterators can't be rewound. If it needs go back, just turn the data into a list first.
>>> next(c)
20
>>> next(c)
21
>>> for x in itertools.islice(c, 10, 20):
... print x
...
32
33
34
35
36
37
38
39
40
41
... while True:
... yield n
... n += 1
...
>>> c = count(0)
>>> c[10:20]
Traceback (most recent call last):
File "
TypeError: 'generator' object has no attribute '__getitem__'
... print x
...
10
11
12
13
14
15
16
17
18
19
islice() will consume data on the iterator. Iterators can't be rewound. If it needs go back, just turn the data into a list first.
>>> next(c)
20
>>> next(c)
21
>>> for x in itertools.islice(c, 10, 20):
... print x
...
32
33
34
35
36
37
38
39
40
41
Comments
Post a Comment
https://gengwg.blogspot.com/