如何找到两个列表之间的匹配并根据匹配写出输出?

时间:2017-04-24 19:29:45

标签: python python-2.7 for-loop if-statement list-comprehension

我不确定我是否适当地提出了问题标题。但是,我试图解释下面的问题。如果你能想到这个问题,请建议适当的标题。

说我有两种类型的列表数据:

list_headers = ['gene_id', 'gene_name', 'trans_id'] 
# these are the features to be mined from each line of `attri_values`

attri_values = 

['gene_id "scaffold_200001.1"', 'gene_version "1"', 'gene_source "jgi"', 'gene_biotype "protein_coding"']
['gene_id "scaffold_200001.1"', 'gene_version "1"', 'trans_id "scaffold_200001.1"', 'transcript_version "1"', 'exon_number "1"', 'gene_source "jgi"', 'gene_biotype "protein_coding"', 'transcript_source "jgi"', 'transcript_biotype "protein_coding"', 'exon_id "scaffold_200001.1.exon1"', 'exon_version "1"']
['gene_id "scaffold_200002.1"', 'gene_version "1"', 'trans_id "scaffold_200002.1"', 'transcript_version "1"', 'exon_number "3"', 'gene_source "jgi"', 'gene_biotype "protein_coding"', 'transcript_source "jgi"', 'transcript_biotype "protein_coding"', 'exon_id "scaffold_200002.1.exon3"', 'exon_version "1"']

我正在尝试根据list in the headerattribute in the attri_values的匹配制作表格。

output = open('gtf_table', 'w')
output.write('\t'.join(list_headers) + '\n') # this will first write the header

# then I want to read each line
for values in attri_values:
    for list in list_headers:
        if values.startswith(list):
            attr_id = ''.join([x for x in attri_values if list in x])
            attr_id = attr_id.replace('"', '').split(' ')[1]
            output.write('\t' + '\t'.join([attr_id]))

        elif not values.startswith(list):
            attr_id = 'NA'
            output.write('\t' + '\t'.join([attr_id]))

        output.write('\n')

问题:当list of list_headers中找到来自values of attri_values的匹配字符串时,一切正常,但是当没有匹配时,会有很多重复&#39 ; NA'

最终预期结果:

gene_id    gene_name    trans_id
scaffold_200001.1    NA    NA
scaffold_200001.1    NA    scaffold_200001.1
scaffold_200002.1    NA    scaffold_200002.1

发布编辑: 这就是我写elif的方式的问题(因为每次不匹配都会写出' NA')。我试图移动{{{}的条件1}}以不同的方式但没有成功。 如果我删除了NA,则会输出(elif丢失)

NA

3 个答案:

答案 0 :(得分:1)

python有一个find字符串方法,您可以使用它来迭代每个attri_values的每个列表标题。尝试使用此功能:

def Get_Match(search_space,search_string):
    start_character = search_space.find(search_string)

    if start_character == -1:
        return "N/A"
    else:
        return search_space[(start_character + len(search_string)):]

for  i in range(len(attri_values_1)):
    for j in range(len(list_headers)):
        print Get_Match(attri_values_1[i],list_headers[j])

答案 1 :(得分:1)

我使用pandas的答案

import pandas as pd

# input data
list_headers = ['gene_id', 'gene_name', 'trans_id']

attri_values = [
['gene_id "scaffold_200001.1"', 'gene_version "1"', 'gene_source "jgi"', 'gene_biotype "protein_coding"'],
['gene_id "scaffold_200001.1"', 'gene_version "1"', 'trans_id "scaffold_200001.1"', 'transcript_version "1"', 'exon_number "1"', 'gene_source "jgi"', 'gene_biotype "protein_coding"', 'transcript_source "jgi"', 'transcript_biotype "protein_coding"', 'exon_id "scaffold_200001.1.exon1"', 'exon_version "1"'],
['gene_id "scaffold_200002.1"', 'gene_version "1"', 'trans_id "scaffold_200002.1"', 'transcript_version "1"', 'exon_number "3"', 'gene_source "jgi"', 'gene_biotype "protein_coding"', 'transcript_source "jgi"', 'transcript_biotype "protein_coding"', 'exon_id "scaffold_200002.1.exon3"', 'exon_version "1"']]

# process input data
attri_values_X = [dict([tuple(b.split())[:2] for b in a]) for a in attri_values]

# Create DataFrame with the desired columns
df = pd.DataFrame(attri_values_X, columns=list_headers)

# print dataframe
print df

输出

               gene_id  gene_name             trans_id
0  "scaffold_200001.1"        NaN                  NaN
1  "scaffold_200001.1"        NaN  "scaffold_200001.1"
2  "scaffold_200002.1"        NaN  "scaffold_200002.1"

没有大熊猫也很容易。我已经给了你attri_values_X,然后你就在那里,只需从字典中删除你不想要的密钥。

答案 2 :(得分:1)

我设法编写了一个有助于解析数据的函数。我试图修改你发布的原始代码,这里的问题复杂化是你存储需要解析的数据的方式,无论如何我无法判断,这里是我的代码:< / p>

def searchHeader(title, values):
    """"
    searchHeader(title, values) --> list 

    *Return all the words of strings in an iterable object in which title is a substring, 
    without including title. Else write 'N\A' for strings that title is not a substring.
    Example:
             >>> seq = ['spam and ham', 'spam is awesome', 'Ham is...!', 'eat cake but not pizza']
             >>> searchHeader('spam', attri_values)
             ['and', 'ham', 'is', 'awesome', 'N\\A', 'N\\A'] 
    """
    res = [] 
    for x in values: 
        if title in x: 
            res.append(x)
        else:
            res.append('N\A')                     # If no match found append N\A for every string in values

    res = ' '.join(res)
    # res = res.replace('"', '')                  You can use this for your code or use it after you call the function on res
    res = res.split(' ')
    res = [x for x in res if x != title]          # Remove title string from res
    return  res 

在这种情况下,正则表达式也很方便。使用此函数解析数据,然后格式化结果以将表写入文件。此函数仅使用一个for循环和一个列表推导,在代码中,您使用两个嵌套的for循环和一个列表推导。

将每个标题字符串分别传递给函数,如下所示:

for title in list_headers: 
    result = searchHeader(title, attri_values)
    ...format as table...
    ...write to file... 

如果可行,请考虑从简单列表移至attri_values的字典,这样您就可以将字符串与其标题分组:

attri_values = {'header': ('data1', 'data2',...)}

在我看来,这比使用列表更好。另请注意,您在代码中覆盖了list名称,这不是一件好事,因为list实际上是创建列表的内置类。