你提到的Python,Perl和awk中。
在所有三者中,这个想法都是一样的:使用散列来存储值。
哈希与数组类似,除了每个条目都使用键索引,而不是位置。在一个散列中,只能有一个关键字。因此,哈希用于检查值是否曾经出现过。下面是一个简单的Perl例如:
my %value_hash;
for my $value (qw(one two three one three four)) {
if (exists $value_hash{$value}) {
print "I've seen the value $value before\n";
}
else {
print "The value of $value is new\n";
$value_hash{$value} = 1;
}
}
这将打印出:
The value of one is new
The value of two is new
The value of three is new
I've seen the value of one before
I've seen the value of three before
The value of four is new
首先,你需要两个循环:一个遍历所有文件,另一个遍历的每一行特定的文件。
for my $file_name (@file_list) {
open my $file_fh, "<", $file_name
or die qw(File $file_name doesn't exist);
while (my $line = <$file_fh>) {
chomp $line;
...
}
}
接下来,我们会为每个氨基酸和那些氨基酸追踪散列的总和介绍哈希:
use strict;
use warnings;
use autodie;
my %total_amino_acids;
my @file_list = qw(file1 file2); #Your list of files
for my $file_name (@file_list) {
open my $file_fh, "<", $file_name;
my %seen_amino_acid_before; # "Initialize" hash which tracks seen
while (my $line = <$file_fh>) {
chomp $line;
my ($location, $amino_acid) = split $line;
if (not %seen_amino_acid_before{$amino_acid}) {
$total_amino_acids{$amino_acid} += 1;
}
}
}
现在,我假设当你说独特 ,你只是在谈论氨基酸而不是位置。 split
正在分裂这两个值,我只看着氨基酸。如果位置也很重要,则必须将其包含在第%seen_amino_acid_before
个散列的密钥中。这是棘手的,因为我可以想象以下内容:
54 LEU
54 LEU
054.00 LEU
这些是不同的字符串,但都具有相同的信息。你想要确保你标准化位置/氨基酸密钥。
while (my $line = <$file_fh>) {
chomp $line;
my ($location, $amino_acid) = split $line;
my $amino_acid_key = sprinf "%04d-%s", $location, uc $amino_acid;
if (not %seen_amino_acid_before{$amino_acid_key}) {
$total_amino_acids{$amino_acid} += 1;
}
}
在上面,我创建了一个$amino_acid_key
。我使用sprintf
将我的数字部分格式化为零填充小数,氨基酸为大写。这样:
54 LEU
54 leu
054.00 Leu
都将是关键0054-LEU
。这样,数据输入到文件中的方式不会影响结果。这可能是一个完全不必要的步骤,但应该始终考虑。例如,如果您的数据是由计算机生成的,那么这可能不是问题。如果您的数据是在半夜中由一群过度劳动的研究生输入的,那么您可能需要担心格式。
现在,所有你需要的是一个循环读取数据:我以前printf
帮助格式化总计
for my $amino_acid (sort keys %total_amino_acids) {
printf "total no:of %4s - %4d\n", $amino_acid, $total_amino_acids{$amino_acid};
}
通知,所以他们会排起长队。
'而TRUE':你需要一个'break'陈述或者你会得到一个无限循环。 – 2013-04-07 04:12:02