加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Perl – 散列和列的哈希:(

发布时间:2020-12-15 23:33:29 所属栏目:大数据 来源:网络整理
导读:我有一组可变大小的字符串,例如: AAA23 AB1D1 A1BC AAB212 我的目标是按字母顺序排列并为COLUMNS收集独特的字符,例如: 第一栏:AAAA 第二栏:AB1A 等等… 在这一刻,我能够通过散列哈希来提取帖子.但是现在,我该如何对数据进行排序?我可以为每个散列哈希创
我有一组可变大小的字符串,例如:

AAA23

AB1D1

A1BC

AAB212

我的目标是按字母顺序排列并为COLUMNS收集独特的字符,例如:

第一栏:AAAA

第二栏:AB1A

等等…

在这一刻,我能够通过散列哈希来提取帖子.但是现在,我该如何对数据进行排序?我可以为每个散列哈希创建一个新数组吗?

非常感谢你的帮助!

我的代码:

#!/usr/bin/perl

use strict;
use warnings;

my @sessions = (
    "AAAA","AAAC","ABAB","ABAD"
);

my $length_max = 0;
my $length_tmp = 0;

my %columns;

foreach my $string (@sessions){

    my $l = length($string);

    if ($l > $length_tmp){
            $length_max = $l;
    }
}

print "max legth : $length_maxnn";

my $n = 1;

foreach my $string (@sessions){

    my @ch = split("",$string);

    for my $col (1..$length_max){
        $columns{$n}{$col} = $ch[$col-1];
    }

    $n++;
}

foreach my $col (keys %columns) {

    print "colonna : $coln";

    my $deref = $columns{$col};

    foreach my $pos (keys %$deref){
            print " posizione : $pos --> $$deref{$pos}n";
    }

    print "n";
}

exit(0);

解决方法

你正在做的是旋转阵列.它不需要哈希或任何东西的哈希,只需要另一个数组.令人惊讶的是,List :: Util和List :: MoreUtils都没有提供.这是一个简单的测试实现.我假设你想要用空格填充的短条目,以便列出来正确.

#!/usr/bin/perl

use strict;
use warnings;

use Test::More;
use List::Util qw(max);

my @Things = qw(
    AAA23
    AB1D1
    A1BC
    AAB212
);


sub rotate {
    my @rows = @_;

    my $maxlength = max map { length $_ } @rows;

    my @columns;
    for my $row (@rows) {
        my @chars = split //,$row;
        for my $colnum (1..$maxlength) {
            my $idx = $colnum - 1;
            $columns[$idx] .= $chars[$idx] || ' ';
        }
    }

    return @columns;
}


sub print_columns {
    my @columns = @_;

    for my $idx (0..$#columns) {
        printf "Column %d: %sn",$idx + 1,$columns[$idx];
    }
}


sub test_rotate {
    is_deeply [rotate @_],[
        "AAAA","AB1A","A1BB","2DC2","31 1","   2",];
}


test_rotate(@Things);
print_columns(@Things);
done_testing;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读