Skip to main content
 首页 » 编程设计

python之边列表中唯一的节点列表

2025年05月04日19over140

我有一个很大的边缘列表(约 2600 万),其中前两列作为节点并且具有可变数量的可选列:

Node1    Node2    OptionalCol1    OptionalCol2   ... 
 
Gene A    Gene D   --             -- 
Gene C    Gene F   --             -- 
Gene D    Gene C   --             -- 
Gene F    Gene A   --             -- 

我想要一个文本文件,其中包含非冗余 节点列表,两者 列。 输出:

Gene A 
Gene D 
Gene C 
Gene F 

我的 python 代码:

file1 = open("input.txt", "r") 
node_id = file1.readlines() 
node_list=[] 
 
for i in node_id: 
    node_info=i.split() 
    node_info[0]=node_info[0].strip() 
    node_info[1]=node_info[1].strip() 
    if node_info[0] not in node_list: 
        node_list.append(node_info[0]) 
    if node_info[1] not in node_list: 
        node_list.append(node_info[1]) 
 
print node_list 

是否可以用 awk 做到这一点?谢谢

请您参考如下方法:

假设分隔符是制表符 (\t)。如果它是一堆空格(一堆不止一个)而不是 -F"\t" 使用:-F"​​+":

$ awk -F"\t" 'NR>2{a[$1];a[$2]}END{for(i in a)print i}' file 
Gene A 
Gene C 
Gene D 
Gene F 

输出没有任何特定的顺序,但它可能是。解释:

$ awk -F"\t" ' 
NR>2 {           # starting on the third record 
    a[$1]        # hash first... 
    a[$2]        # and second columns 
} 
END {            # after all that hashing 
    for(i in a)  # iterate whole hash 
        print i  # and output 
}' file