在python中获取两个列表的交集

在python中获取两个列表的交集,python,list,sorting,bioinformatics,Python,List,Sorting,Bioinformatics,我有两个我正在分析的基因列表。本质上,我想以与维恩图相同的方式对这些列表中的元素进行排序,也就是说,只出现在列表1中的元素放在一个列表中,只出现在列表2中的元素放在另一个列表中,同时出现在两个列表中的元素放在第三个列表中 到目前为止,我的代码是: from Identify_Gene import Retrieve_Data #custom class import argparse import os #enable use from command line parser = argpar

我有两个我正在分析的基因列表。本质上,我想以与维恩图相同的方式对这些列表中的元素进行排序,也就是说,只出现在列表1中的元素放在一个列表中,只出现在列表2中的元素放在另一个列表中,同时出现在两个列表中的元素放在第三个列表中

到目前为止,我的代码是:

from Identify_Gene import Retrieve_Data #custom class
import argparse
import os

#enable use from command line
parser = argparse.ArgumentParser(description='''\n\nFind the intersection between two lists of genes\n ''')
parser.add_argument('filename1',help='first list of genes to compare')
parser.add_argument('filename2',help='second list of genes to compare')
parser.add_argument('--output_path',help='provide an output filename')
args = parser.parse_args()

os.chdir(args.output_path)

a = Retrieve_Data() # custom class, simply produces a python list
list1 = a.parse_gene_list(args.filename1)
list2 = a.parse_gene_list(args.filename2)

intersection = []
list1_only = []
list2_only = []
if len(list1)>len(list2):
    for i in range(0,len(list1)):
        if list1[i] in list2:
            intersection.append(list1[i])
        else:
            list1_only.append(list1[i])
    for i in range(0,len(list2)):
        if list2[i] not in list1:
            list2_only.append(list2[i])
else:
    for i in range(0,len(list2)):
        if list2[i] in list1:
            intersection.append(list2[i])
        else:
            list2_only.append(list2[i])
    for i in range(0,len(list1)):
        if list1[i] not in list2:
            list1_only.append(list2[i])




filenames = {}
filenames['filename1'] = 'list1_only.txt'
filenames['filename2'] = 'list2_only.txt'
filenames['intersection'] = 'intersection.txt'                

with open(filenames['filename1'],'w') as f:
    for i in range(0,len(list1_only)):
        f.write(list1_only[i]+'\n')

with open(filenames['filename2'],'w') as f:
    for i in range(0,len(list2_only)):
        f.write(list2_only[i]+'\n')

with open(filenames['intersection'],'w') as f:
    for i in range(0,len(intersection)):
        f.write(intersection[i]+'\n')
该程序目前为我提供了两个相同的列表,分别为list1_only和list2_only,它们应该相互排斥。生成的交集文件是不同的,尽管我觉得它不可信,因为其他两个列表的行为不符合预期


我被告知(在发布这个问题之后),这个操作可以通过python的“集合”模块轻松完成。但是,出于教育目的,我还是很想修复这个程序。列表的构造中有一个bug

在本节中:

for i in range(0,len(list1)):
    if list1[i] not in list2:
        list1_only.append(list2[i])
最后一行应该是:

        list1_only.append(list1[i])

您可能还希望签出此方便的网站:


您尝试过使用集合吗?我没有,那是python模块吗?是一个内置的。这是一个很好的方法,如果你所有的项目都可以散列。这正是我想要的,谢谢。