requirements : 40 Elements of the array, according to 8 per line, divided into 5 lines printed out. Such as
1 2 3 4 5 6 7 8
9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24
25 26 27 28 29 30 31 32
33 34 35 36 37 38 39 40
cause : There are some scenarios for working with data files, such as averaging per 8 rows, maximum value, or something else, which can be abstracted to one array per 8 lines, and then processed directly to the array
1 #!/usr/bin/perl -w
2 use strict;
3
4 my @data = 1..40;
5
6 my $window = 8;
7
8 for my $loop(0..(@data/$window)-1)
9 {
10 my @tmp = ();
11 for my $index (0..($window-1))
12 {
13 push @tmp, $data[$index + $window * $loop];
14 }
15 print join("\t", @tmp), "\n";
16 }
Analysis: The principle is very simple, to find the rules of the index, it is, but every time can not be remembered quickly, hereby record. The key is to use Line8, Line13, to find the correct formula for the index.
0+8*0, 1+8*0, ... 7+8*0
0+8*1, 1+8*1, ... 7+8*1
...
0+8*4, 1+8*4, ... 7+8*4
Promotion: Other languages can also be done according to this idea
1 #!/usr/bin/python
2
3 data = range(40)
4
5 window = 8
6
7 for loop in range(len(data)/window):
8 tmp = []
9 for index in range(window):
10 tmp.append(data[index + window * loop])
11 #print tmp
12 print "\t".join([str(x) for x in tmp])
not very good idea : The first is to think of arithmetic progression formula, first find out each row (representing a row array) of a value, followed by arithmetic progression formula a1+ (n-1) *d, in turn, the code is a bit verbose
1 #!/usr/bin/perl -w
2 use strict;
3
4 my @data = 1..40;
5
6 my $window = 8;
7 my $offset = 1;
8
9 my @tmp = ();
10 for my $loop(0..(@data/$window - 1))
11 {
12 my $first = $data[0] + $loop * $window;
13 for my $index(1..$window)
14 {
15 my $value = $first + ($index - 1) * $offset;
16 push @tmp, $value;
17 }
18 print "@tmp\n";
19 @tmp = ();
20 }
Split array by number of fixed elements-Perl,python