0

如果你有一个名字列表。. .

query = ['link','zelda','saria','ganon','volvagia']

和文件中的行列表

data = ['>link is the first','OIGFHFH','AGIUUIIUFG','>peach is the second',
'AGFDA','AFGDSGGGH','>luigi is the third','SAGSGFFG','AFGDFGDFG',
'DSGSFGAAA','>ganon is the fourth','ADGGHHHHHH','>volvagia is the last',
 'AFGDAAFGDA','ADFGAFD','ADFDFFDDFG','AHUUERR','>ness is another','ADFGGGGH',
'HHHDFDA']

您将如何查看以“>”开头的所有行,然后如果它们具有名称 name_list 之一,则包括带有“>”的行以及它后面的序列(后面的序列总是在上面)在两个单独的列表中

#example output file

name_list = ['>link is the first','>ganon is the fourth','>volvagia is the last']
seq_list = ['OIGFHFHAGIUUIIUFG','ADGGHHHHHH','AFGDAAFGDAADFGAFDADFDFFDDFGAHUUERR']

我宁愿不使用字典来执行此操作,因为在类似情况下我被提示这样做

所以我到目前为止是:

for line,name in zip(data,query):
    if bool(line[0] == '>' and re.search(name,line))==True:
        #but then i'm stuck because len(query) and len(data) are not equal

....任何帮助将不胜感激``

4

3 回答 3

1
result = []
names = ['link', 'zelda', 'saria', 'ganon', 'volvagia']
lines = iter(data)
for line in lines:
    while line.startswith(">") and any(name in line for name in names):
        name = line
        upper_seq = []
        for line in lines:
            if not line.isupper():
                break
            upper_seq.append(line)
        else:
            line = "" # guard against infinite loop at EOF 

        result.append((name, ''.join(upper_seq)))

如果有很多名称,那么set()在行中查找名称可能会更快,而不是any(...)

names = set(names)
# ...
    if line.startswith(">") and names.intersection(line[1:].split()):
        # ...

结果

[('>link is the first', 'OIGFHFHAGIUUIIUFG'),
 ('>ganon is the fourth', 'ADGGHHHHHH'),
 ('>volvagia is the last', 'AFGDAAFGDAADFGAFDADFDFFDDFGAHUUERR')]
于 2013-03-11T22:05:09.107 回答
0

使用列表理解

print [line for line in lines if line.startswith(">") and set(my_words).intersection(line[1:].split())]

这分解为一个for循环,如下所示

matched_line = []
for line in lines:
    if line.startswith(">") and set(my_words).intersection(line[1:].split()):
       matched_lines.append(line)

使用集合交集应该比遍历列表中的每个单词并查看它是否在字符串中要快得多

>>> print [line for line in data if line.startswith(">") and set(query).intersection(line[1:].split())]
['>link is the first', '>ganon is the fourth', '>volvagia is the last']
于 2013-03-11T21:38:56.720 回答
0

有更优雅的方法可以做到这一点,但我认为这种方法可能是你最容易理解的:

>>> found_lines = []
>>> sequences = []
>>> for line in data:
...     if line.startswith(">"):
...         for name in query:
...             if name in line:
...                 found_lines.append(line)
...     else:
...         sequences.append(line)
>>> print found_lines
['>link is the first', '>ganon is the fourth', '>volvagia is the last']
>>> 

总是从简单开始,然后想办法解决问题。你需要做的第一件事是什么?您想遍历data( for line in data) 中的每一行。

对于这些行中的每一行,您要检查它是否以>. ( if line.startswith(">"))。如果它不是以那个字符开头,那么我们可以假设它是一个“序列”,并将它添加到sequences列表中 ( sequences.append(line))

如果是这样,那么您要检查是否有任何名称query出现在该行中。最简单的方法是什么?遍历每个名​​称 ( for name in query),并自行检查 ( if name in line)

于 2013-03-11T21:53:30.357 回答