【问题标题】:How to print each array in 2d array vertically in perl如何在perl中垂直打印二维数组中的每个数组
【发布时间】:2014-02-19 20:04:06
【问题描述】:

我有一个 2d perl 数组,我想垂直打印每个数组,但是,我不知道最大数组的大小。我将如何遍历矩阵?

我的@AoA = (
["abc", "def", 1, 2, 3],
[“废话”,“废话2”,2],
[“你好”、“世界”、“怎么样”、“是”、“你”、“在做什么?”],
);

想要的输出:

abc blah hello
def blah2 world
1 2 how
2 null are
3 null you
null null doing

【问题讨论】:

  • 您已更改所需的输出。这是故意的吗?

标签: perl


【解决方案1】:

最好的方法是扫描你的数据两次:首先确定列中的最大项目数和项目的最大宽度,然后实际显示数据。

这个程序演示

use strict;
use warnings;

my @AoA = (
  ["abc", "def", 1, 2, 3],
  ["blah", "blah2", 2],    
  ["hello", "world", "how", "are", "you", "doing?"],
);

my $maxrow;
my $maxwidth;
for my $col (@AoA) {
  my $rows = $#$col;
  $maxrow = $rows unless $maxrow and $maxrow >= $rows;
  for my $item (@$col) {
    my $width = length $item;
    $maxwidth = $width unless $maxwidth and $maxwidth >= $width;
  }
}

for my $row (0 .. $maxrow) {
  my $line = join ' ', map sprintf('%-*s', $maxwidth, $_->[$row] // ''), @AoA;
  print $line, "\n";
}

输出

abc    blah   hello 
def    blah2  world 
1      2      how   
2             are   
3             you   
              doing?

更新

提供修改后的输出要容易得多,因为无需计算最大字段宽度。

use strict;
use warnings;

my @AoA = (
  ["abc", "def", 1, 2, 3],
  ["blah", "blah2", 2],    
  ["hello", "world", "how", "are", "you", "doing?"],
);

my $maxrow;
for my $col (@AoA) {
  $maxrow = $#$col unless $maxrow and $maxrow >= $#$col;
}

for my $row (0 .. $maxrow) {
  print join(' ', map $_->[$row] // 'null', @AoA), "\n";
}

输出

abc blah hello
def blah2 world
1 2 how
2 null are
3 null you
null null doing?

【讨论】:

    【解决方案2】:
    use List::Util qw(max);
    
    # calculate length of longest sub-array
    my $n = max map { scalar(@$_) } @AoA;
    
    for (my $i = 0; $i < $n; ++$i) {
        # the inner map{} pulls the $i'th element of each array,
        # replacing it with 'null' if $i is beyond the end;
        # each piece is then joined together with a space inbetween
    
        print join(' ', map { $i < @$_ ? $_->[$i] : 'null' } @AoA) . "\n";
    }
    

    输出

    abc blah hello
    def blah2 world
    1 2 how
    2 null are
    3 null you
    null null doing?
    

    这有点密集且难以阅读。您可以通过将print 行拆分为多行来使其更具可读性(一行创建所有$i'th 元素的临时数组,另一行将它们连接在一起,另一行打印结果)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-02
      • 1970-01-01
      • 2011-01-22
      • 1970-01-01
      • 2011-10-31
      • 1970-01-01
      • 1970-01-01
      • 2016-07-11
      相关资源
      最近更新 更多