2014-10-27 31 views
0

我在perl中有列和行的多維哈希。perl hash - 重新索引到緊湊值的最佳方式

什麼是壓縮/它重新索引以最好的方式,即用價值,是少的下一行指數

  • 刪除空列
  • 刪除空行
  • 重新編制單個項目/細胞比當前行索引
  • 具有值的單個項目/單元格不需要僅更改行的列。

謝謝你......

下面是一個簡單的哈希在結構上與我有什麼相似:

foreach $i (1..5) { 
    $column = int(rand(10)) +1; 

    foreach $j (1..10) { 
    $row = int(rand(10)) +1; 
    $value = int(rand(1000)) +1; 

    $hash{$column}{$row} = $value if !$hash{$column}{$row}; 
    } 
} 

+ ------------ -------------------------------------- +

我將它轉換爲一個數組陣列。

我能夠壓縮列,但我無法刪除空列。我知道它與切片有關,但無法弄清楚正確的語法。

#AoA - Before# 

$VAR1 = [ 
     undef, 
     [ 
     undef, 
     4, 
     0, 
     61, 
     0, 
     22 
     ], 
     [ 
     undef, 
     0, 
     0, 
     0, 
     0, 
     0 
     ], 
     [ 
     undef, 
     0, 
     12, 
     50, 
     0, 
     66 
     ], 
     [ 
     undef, 
     70, 
     42, 
     22, 
     0, 
     0 
     ] 
    ]; 


foreach $column ([email protected] -1) { 
    ### Compact column 
    @{$AoA[$column]} = grep { ($_) } @{$AoA[$column]}; 


    ### Remove empty column 
    ### What is the correct syntax for this??? 
    # if(!(scalar @{$AoA[$column]})) { 
    # splice(@AoA, $column, 1); 
    # } 
} 


#AoA - After# 
$VAR1 = [ 
     [], 
     [ 
     4, 
     61, 
     22 
     ], 
     [], 
     [ 
     12, 
     50, 
     66 
     ], 
     [ 
     70, 
     42, 
     22 
     ] 
    ]; 
+1

可以前後重新索引你提到後顯示的例子嗎?更好的是,運行你顯示的代碼,顯示數據結構的轉儲(例如'print Data :: Dumper :: Dumper(\%hash)'的輸出),然後在你想要的所有更改之後顯示它的外觀 – ysth 2014-10-28 00:40:14

回答

0

看看Data::Table,它提供了幾個功能,可以讓你做你想做的。

示例表

my $t = new Data::Table([ ["John", 20], ["Kate", 18], ["Mike", 23] ], ["name", "age"], 0); 
my $t1 = new Data::Table; # This is the final clean table 

例如,得到一個新的表沒有空行

$t1=$t->match_pattern('join('',$_)-> =~ //'); 

查找並刪除空列

my $columns_keep = {}; 
$t->colsMap(sub { $columns_keep{ $_->[$colIndex] }="1" if $_->[0]; }); 
$t1.addCols($t->delCols(keys $columns_keep )); 
0

這是我想出了一個解決方案。似乎工作很好。讓我知道是否有更好的方法。

給定一個數組陣列。刪除列中的空單元格,然後刪除空列。

可變的結構(見原題的編輯):$AoA[$column][$row]

### Compact columns. 
foreach $column ([email protected] -1) { 
    @{$AoA[$column]} = grep { $_ } @{$AoA[$column]}; 
} 

### Remove empty columns 
@AoA = grep { scalar @{$_} } @AoA;