Perl 如何计算两个数组中每个元素之间的差异?
我有一个带有数字的文本文件,我将其分组如下,用空行分隔:Perl 如何计算两个数组中每个元素之间的差异?,perl,matrix,perl-data-structures,Perl,Matrix,Perl Data Structures,我有一个带有数字的文本文件,我将其分组如下,用空行分隔: 42.034 41.630 40.158 26.823 26.366 25.289 23.949 34.712 35.133 35.185 35.577 28.463 28.412 30.831 33.490 33.839 32.059 32.072 33.425 33.349 34.709 12.596 13.332 12.810 13.329 13.329 13.569 11.418 注:组的长度始终相等,如果组较大,则可以安
42.034 41.630 40.158 26.823 26.366 25.289 23.949
34.712 35.133 35.185 35.577 28.463 28.412 30.831
33.490 33.839 32.059 32.072 33.425 33.349 34.709
12.596 13.332 12.810 13.329 13.329 13.569 11.418
注:组的长度始终相等,如果组较大,则可以安排在多行中,例如500个数字长。
我正在考虑将这些组放入数组中,并沿着文件的长度进行迭代
我的第一个问题是:我应该如何从数组1中减去数组2的第一个元素,从数组2中减去数组3,同样地,从第二个元素中减去第二个元素,依此类推,直到组的末尾
i、 e:
然后将第一个元素在一组中的差异保存到最后(第二个问题:如何?)
i、 e:
我是初学者,所以任何建议都会很有帮助。假设您打开了文件,下面是一个快速草图
use List::MoreUtils qw<pairwise>;
...
my @list1 = split ' ', <$file_handle>;
my @list2 = split ' ', <$file_handle>;
my @diff = pairwise { $a - $b } @list1, @list2;
以下是使Axeman的代码正常工作的其余基础结构:
#!/usr/bin/perl
use strict;
use warnings;
use List::MoreUtils qw<pairwise>;
my (@prev_line, @this_line, @diff);
while (<>) {
next if /^\s+$/; # skip leading blank lines, if any
@prev_line = split;
last;
}
# get the rest of the lines, calculating and printing the difference,
# then saving this line's values in the previous line's values for the next
# set of differences
while (<>) {
next if /^\s+$/; # skip embedded blank lines
@this_line = split;
@diff = pairwise { $a - $b } @this_line, @prev_line;
print join(" ; ", @diff), "\n\n";
@prev_line = @this_line;
}
您将获得:
2 ; 1 ; 0
-1 ; 0 ; 1
谢谢你的回复,我在这里有点困惑,我的@list1=split';我的@list2=拆分“”;因此,你将文件按空行分割,并将其分配到数组中。据我所知,我在一段时间内尝试了它(),以便它每次读取整个文件并将2个组分配到数组中。当我尝试循环时,@list2不包含任何内容(使用两两)。我被困在这里了,你能给我更多的建议吗
# construct a list using each index in @list1 ( 0..$#list1 )
# consisting of the difference at each slot.
my @diff = map { $list1[$_] - $list2[$_] } 0..$#list1;
#!/usr/bin/perl
use strict;
use warnings;
use List::MoreUtils qw<pairwise>;
my (@prev_line, @this_line, @diff);
while (<>) {
next if /^\s+$/; # skip leading blank lines, if any
@prev_line = split;
last;
}
# get the rest of the lines, calculating and printing the difference,
# then saving this line's values in the previous line's values for the next
# set of differences
while (<>) {
next if /^\s+$/; # skip embedded blank lines
@this_line = split;
@diff = pairwise { $a - $b } @this_line, @prev_line;
print join(" ; ", @diff), "\n\n";
@prev_line = @this_line;
}
1 1 1
3 2 1
2 2 2
2 ; 1 ; 0
-1 ; 0 ; 1