首页 > 解决方案 > 比较两个网络边缘列表

问题描述

我有两个列表 - master.txt 和它的一个子集 child.txt。我想在 master.txt 中打印 child.txt 中不存在的边缘

大师.txt

A    B
B    C
D    F

子.txt

B    A
C    B
E    F

输出:DF

我写了一个示例代码

file1 = open("master.txt", "r")
file2 = open("child.txt", "r")
probe_id = file1.readlines()
loc_names = file2.readlines()`
#flag=0
for i in probe_id:
    i=i.rstrip()
    probe_info=i.split("\t")
    probe_info[0]=probe_info[0].strip()
    probe_info[1]=probe_info[1].strip()
    flag=0
    for j in loc_names:
        j=j.strip()
        loc_names=j.split("\t")
        loc_names[0]=loc_names[0].strip()
        loc_names[1]=loc_names[1].strip()  #throwing index out of range error
        if (probe_info[0]==loc_names[0] and probe_info[1]==loc_names[1]) or (probe_info[0]==loc_names[1] and probe_info[1]==loc_names[0]):
            flag=1
        if flag==0:
            print i

截至目前,当我拆分较小的文件时,我的索引超出了范围。请帮忙。此外,如果有任何其他更快的技术来做同样的事情,请告诉我。谢谢

标签: pythonawk

解决方案


如果我正确理解您的要求,那么您只需要:

$ awk '
    { edge=($1>$2 ? $1 FS $2 : $2 FS $1) }
    NR==FNR{ file1[edge]; next }
    !(edge in file1)
' child.txt master.txt
D    F

如果您想在子节点中找到不在 master 中的边,您只需翻转输入文件的顺序:

$ awk '
    { edge=($1>$2 ? $1 FS $2 : $2 FS $1) }
    NR==FNR{ file1[edge]; next }
    !(edge in file1)
' master.txt child.txt
E    F

以上将非常快,因为它只是进行哈希查找。


推荐阅读