"A", "AAAA" -6ren">
gpt4 book ai didi

arrays - 在 Perl 中迭代哈希和数组

转载 作者:行者123 更新时间:2023-12-02 05:57:04 26 4
gpt4 key购买 nike

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

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

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

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

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

我不知道我是否已经足够好地解释了我的问题,但如果这不起作用,我就无法继续我的代码......

提前非常感谢。

最佳答案

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

尝试而不是

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" );
}

关于arrays - 在 Perl 中迭代哈希和数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19682186/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com