我在第一列中有两个字符串对,在第一列中用空格分隔,还有两个列有值。我想要创建一个新的文件,在这个文件中,字符串对在同一行中匹配,而不管它们的顺序如何。例如,打印包含对"GAT_1 GAT_2“的行和它旁边包含"GAT_2 GAT_1”的行。在将每个字符串赋值给给定对的变量之后,如何不重复地比较不同行的字符串呢?
# discard headers
foreach $line (@file) {
@columns = split (/\t/, $line);
@strings = split (/\s/, $columns[0]);
# pseudocode:
foreach line that has pair "$strings[0] $strings[1]" {
print $line,"\t", and $line where pair is "$strings[1] $strings[0]"
Input:
pair val1 val2
GAT_1 GAT_2 0.2 4.5
GAT_1 GAT_3 0.1 0.2
GAT_4 GAT_5 0.9 7.5
GAT_5 GAT_4 0.5 8.3
BLAC BABA 8.3 1.3
BABA BLAC 8.9 1.1
GAT_2 GAT_1 1.2 2.1
GAT_3 GAT_1 3.4 4.3
Ouput:
pair val1 val2 pair val1 val2
GAT_1 GAT_2 0.2 4.5 GAT_2 GAT_1 1.2 2.1
GAT_1 GAT_3 0.1 0.2 GAT_3 GAT_1 3.4 4.3
GAT_4 GAT_5 0.9 7.5 GAT_5 GAT_4 0.5 8.3
BLAC BABA 8.3 1.3 BABA BLAC 8.9 1.1发布于 2015-12-09 21:31:30
这里有一种解决这个问题的方法,它适用于任意数量的值列。基本的方法是我在comment中建议的方法,即将键规范化,然后将我们找到的任何值推送到数组中。
use strict;
use warnings;
my %unique;
while (<DATA>) {
chomp;
next unless /^\S/;
my @fields = split;
my $key = join(' ', sort(splice(@fields, 0, 2)));
push(@{$unique{$key}}, @fields);
}
for my $key (keys(%unique)) {
print join("\t", $key, @{$unique{$key}});
print "\n";
}
__DATA__
pair val1 val2
GAT_1 GAT_2 0.2 4.5
GAT_1 GAT_3 0.1 0.2
GAT_4 GAT_5 0.9 7.5
GAT_5 GAT_4 0.5 8.3
BLAC BABA 8.3 1.3
BABA BLAC 8.9 1.1
GAT_2 GAT_1 1.2 2.1
GAT_3 GAT_1 3.4 4.3输出:
GAT_4 GAT_5 0.9 7.5 0.5 8.3
GAT_1 GAT_2 0.2 4.5 1.2 2.1
BABA BLAC 8.3 1.3 8.9 1.1
GAT_1 GAT_3 0.1 0.2 3.4 4.3发布于 2015-12-09 21:51:19
https://stackoverflow.com/a/34189380/103780中的小改动将给您想要的东西:(未经测试):my @keys = splice(@fields, 0, 2); my $key = join(' ', @keys); my $skey = join (' ', sort @keys); push(@{$unique{$skey}{$key}}, @fields);
for my $skey (keys(%unique)) { for my $key (keys(%unique{$skey})) { print join("\t", $key, @{$unique{$skey}{$key}}); print "\t"; } print "\n"; }
https://stackoverflow.com/questions/34187313
复制相似问题