你将如何创建和遍历散列(深度为n)的散列,从而深度n处的值是整数? [英] How would you create and traverse a hash of hashes (of depth n), whereby the values at depth n are integers?

查看:145
本文介绍了你将如何创建和遍历散列(深度为n)的散列,从而深度n处的值是整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在所描述的数据结构中存储大小为n的DNA序列。每个散列可以包含将具有散列值的键C,G,A,T。这些散列值将是完全相同的散列值 - 它们将具有四个密钥C,G,A,T,它们将具有散列值。

这个结构对于n个哈希级别是一致的。但是,最后一个散列值将具有整数值,它表示从级别1到级别n的序列数量。给定数据('CG','CA','TT','CG'),表示序列CG,CA和TT发生两次,一次,一次。对于这个数据,深度为2。



这会产生一个哈希值:
%root =('C'=> {'G'=> 2,'A'=> 1},'T'=> {'T'=> 1})

如何从数据创建散列?

解决方案

您需要的是一个函数 get_node($ tree,'C','G')返回对CG散列元素的引用。然后你可以增加引用的标量。

  sub get_node {
my $ p = \shift;
$ p = \(($$ p) - > {$ _})for @_;
返回$ p;
}

my @seqs = qw(CG CA TT CG);

my $ tree;
++ $ {get_node($ tree,split //)} for @seqs;

事情是,这个函数已经存在为 Data :: Diver DiveRef

 使用Data :: Diver qw(DiveRef); 

my @seqs = qw(CG CA TT CG);

my $ tree = {};
++ $ {DiveRef($ tree,split //)} for @seqs;在这两种情况下,
$ b

> 使用Data :: Dumper qw(Dumper);
print(Dumper($ tree));

打印

  $ VAR1 = {
'T'=> {
'T'=> 1
},
'C'=> {
'A'=> 1,
'G'=> 2
}
};


I want to store DNA sequences of size n in the described data structure. Each hash could contain the keys C,G,A,T who will have hash values. These hash values will be the exact same kind of hashes - they will have four keys, C,G,A,T who will have hash values.

This structure is consistent for n levels of hashes. However, the last level of hashes will instead have integer values, which represent the count of the sequence from level 1 to level n.

Given the data ('CG', 'CA', 'TT', 'CG'), indicating that the sequences CG, CA, and TT occurred twice, once, and once. For this data, the depth would be 2.

This would produce a hash: %root = ( 'C' => { 'G' => 2, 'A' => 1}, 'T' => {'T' => 1 })

How would one create this hash from the data?

解决方案

What you need is a function get_node($tree, 'C', 'G') returns a reference to the hash element for "CG". Then you can just increment the referenced scalar.

sub get_node {
   my $p = \shift;
   $p = \( ($$p)->{$_} ) for @_;
   return $p;
}

my @seqs = qw( CG CA TT CG );

my $tree;
++${ get_node($tree, split //) } for @seqs;

The thing is, this function already exists as Data::Diver's DiveRef.

use Data::Diver qw( DiveRef );

my @seqs = qw( CG CA TT CG );

my $tree = {};
++${ DiveRef($tree, split //) } for @seqs;

In both case,

use Data::Dumper qw( Dumper );
print(Dumper($tree));

prints

$VAR1 = {
          'T' => {
                   'T' => 1
                 },
          'C' => {
                   'A' => 1,
                   'G' => 2
                 }
        };

这篇关于你将如何创建和遍历散列(深度为n)的散列,从而深度n处的值是整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆