簡體   English   中英

在Python中獲取兩個列表的交集

[英]Getting intersection of two lists in python

我有兩個要分析的基因清單。 本質上,我想對這些列表中的元素進行排序的方式與Venn圖大致相同,即僅將出現在列表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'Sets'模塊輕松完成此操作,但是,出於教育目的,我還是很想修復此程序

列表的構造中存在錯誤。

在此部分中:

for i in range(0,len(list1)):
    if list1[i] not in list2:
        list1_only.append(list2[i])

最后一行應該是:

        list1_only.append(list1[i])

您可能還想簽出這個方便的網站:

http://jura.wi.mit.edu/bioc/tools/compare.php

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM