如何计算两个数组中每个元素之间的差异?

时间:2011-03-01 14:52:04

标签: 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

注意:组长度总是相等的,并且如果组很大,可以排列多于一行,比如500个数字。 我正在考虑将这些组放在数组中并沿着文件的长度进行迭代。

我的第一个问题是:我应该如何从数组1中减去数组2的第一个元素,从数组2中减去数组3,对第二个元素类似,依此类推直到组的结尾?

即:

34.712-42.034,35.133-41.630,35.185-40.158 ...till the end of each group

33.490-34.712,33.839-35.133   ..................

然后将第一个元素的差异保存在一个组中(第二个问题:如何?)直到结束

即:

34.712-42.034 ; 33.490-34.712 ; and so on in one group

35.133-41.630 ; 33.839-35.133 ; ........

我是初学者,所以任何建议都会有所帮助。

2 个答案:

答案 0 :(得分:6)

假设您打开了文件,以下是快速草图

use List::MoreUtils qw<pairwise>;
...

my @list1 = split ' ', <$file_handle>;
my @list2 = split ' ', <$file_handle>;

my @diff  = pairwise { $a - $b } @list1, @list2;

pairwise是最简单的方式。

否则就有旧备用:

# construct a list using each index in @list1 ( 0..$#list1 )
# consisting of the difference at each slot.
my @diff = map { $list1[$_] - $list2[$_] } 0..$#list1;

答案 1 :(得分:0)

以下是使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;
}

所以给出了输入:

1 1 1

3 2 1

2 2 2

你会得到:

2 ; 1 ; 0

-1 ; 0 ; 1