首页 > 解决方案 > 边列表中节点的唯一列表

问题描述

我有一个大边缘列表(约 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 做到这一点吗?谢谢

标签: pythonawk

解决方案


假设分隔符是制表符 ( \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

推荐阅读