【问题标题】:Iterate through a hash and an array in Perl遍历 Perl 中的哈希和数组
【发布时间】:2013-11-10 00:32:36
【问题描述】:

我有一个数组和一个哈希:

@arraycodons = "AATG", "AAAA", "TTGC"... etc.
%hashdictionary = ("AATG" => "A", "AAAA" => "B"... etc.)

我需要将数组的每个元素转换为 hashdictionary 中的相应值。但是,我得到一个错误的翻译.....

为了查看问题,我打印了 $codon(数组的每个元素),但是每个密码子都重复了好几次.....它不应该。

sub translation() {
    foreach $codon (@arraycodons) {
        foreach $k (keys %hashdictionary) {
            if ($codon == $k) {
                $v = $hashdictionary{$k};
                print $codon;
            }
        }
    }
}

我不知道我是否已经充分解释了我的问题,但如果这不起作用,我将无法继续使用我的代码...

非常感谢。

【问题讨论】:

  • 使用eq 进行字符串比较,而不是==

标签: arrays perl loops hash


【解决方案1】:

您似乎在遍历哈希键(也称为“字典”)以找到所需的键。这违背了散列(也称为“字典”)的目的 - 其主要优点是超快速的键查找。

尝试,而不是

foreach $codon (@arraycodons) {
    foreach $k (keys %hashdictionary) {
        if ($codon == $k) {
            $v = $hashdictionary{$k};
            print $codon;
        }
    }
}

这个:

foreach $codon (@arraycodons) {
    my $value = $hashdictionary{$codon};
    print( "$codon => $value\n" );
}

或:

foreach my $key ( keys %hashdictionary ) {
    my $value = $hashdictionary{$key};
    print( "$key => $value\n" );
}

【讨论】:

    【解决方案2】:
    my @mappedcodons = map {$hashdictionary{$_}} 
                      grep (defined $hashdictionary{$_},@arraycodons);
    

    my @mappedcodons = grep ($_ ne "", map{$hashdictionary{$_} || ""} @arraycodons);
    

    【讨论】:

    • 没有映射的单词怎么办?考虑$hashdictionary{$_} // $_
    • 添加过滤(原代码没有打印不匹配的条目)
    【解决方案3】:
    my @words = ("car", "house", "world"); 
    my %dictionary = ("car" => "el coche", "house" => "la casa", "world" => "el mundo"); 
    my @keys = keys %dictionary; 
    
    
    foreach(@words) {
    my $word = $_; 
    foreach(@keys) {
        if($_ eq $word) { # eq, not ==
            my $translation = $dictionary{$_}; 
            print "The Spanish translation of $word is $translation\n"; 
        }
    
    }
    }
    

    【讨论】:

    • 内循环和if等价于my $translation = $dictionary{$word},见@PP.的回答。
    • 是的,不需要迭代。只是想大致坚持作者的代码......我自己可能会写一些与 Ashalynd 的答案类似的东西,它非常“失败”。
    猜你喜欢
    • 2012-08-22
    • 2019-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-21
    • 2013-02-09
    • 2011-10-28
    相关资源
    最近更新 更多