[Tutor] skip/slice more than every second?
Steven D'Aprano
steve at pearwood.info
Tue Sep 29 05:55:41 CEST 2015
On Tue, Sep 29, 2015 at 01:16:36PM +1000, questions anon wrote:
> a = [1,2,3,4,5,6,7,8,9,10,11,12,13,14]
>
> how can I show the first then skip three and show the next and so on?
> For example:
> show 1
> then skip 2,3,4
> then show 5
> then skip 6,7,8
> then show 9
> then skip 10,11,12,
Here is one method, using slicing:
py> a = [1,2,3,4,5,6,7,8,9,10,11,12,13,14]
py> a[::4]
[1, 5, 9, 13]
The slice a[::4] is equivalent to a[0:len(a):4], that is, it starts at
position 0, keeps going until the end, and extracts every fourth value.
Here is another method:
py> it = iter(a)
py> while True:
... try:
... print(next(it))
... who_cares = next(it), next(it), next(it)
... except StopIteration:
... break
...
1
5
9
13
This grabs each item in turn, prints the first, then throws away three,
then prints the next, and so on. This is a good technique for when you
want something that doesn't fit into the fairly simple patterns
available using slicing, e.g.:
- print 1 item;
- throw away 2;
- print 3 items;
- throw away 4;
- print 5 items;
- throw away 6;
- print 7 items;
- throw away 8;
etc.
But for cases where slicing does the job, it is better to use that.
--
Steve
More information about the Tutor
mailing list