解决方案:
pattern = 'AAA'
with open('practice_data.txt') as f_dna:
dna_list = [sequence for line in f_dna for sequence in line.split()]
print(smallest_distance(pattern, dna_list))
说明:
你是接近的解决方案,但你需要通过split()
到remplace strip()
- >strip()
删除多余的字符,所以你strip('\n')
是一个很好的猜测。 但由于\n
是在该行的结束,因为这是算作一个delimitor拆分将自动摆脱它
如
>>> 'test\ntest'.split()
>>> ['test', 'test']
>>> 'test\n'.split()
>>> ['test']
现在,你必须通过列表之间的简单相加remplace .append()
自分割以来的操作返回list
。
DNA = open('practice_data.txt')
empty = []
for lines in DNA:
line = lines.split()
empty += line
但,还有在你的代码中的一些问题:
这是更好地使用with
声明在打开一个文件,因为它会自动处理异常,并在年底关闭文件描述符:
empty = []
with open('practice_data.txt') as DNA:
for lines in DNA:
line = lines.split()
empty += line
你的代码现在很好,你仍然可以使用重构列表理解(Python中很常见)
with open('practice_data.txt') as DNA:
empty = [sequence for line in DNA for sequence in line.split()]
如果您对此有所了解,尝试以重新组织它循环
empty = []
with open('practice_data.txt') as DNA:
for line in DNA:
for sequence in line.split():
empty.append(sequence)
注意:@MrGeek解决方案工作,但作为两个主要的默认设置:
- ,因为它没有使用
with
声明,该文件是永远不会关闭,导致内存问题,
- 使用
.read().splitlines()
将加载内存中的文件的所有内容,这可能导致MemoryError
例外,如果该文件太大。
走得更远,处理大文件:
,你必须充满DNA序列的1GO文件,即使你不加载在内存中的所有文件
现在成像,你仍然有巨大的dict
,更好的初步实践将创造结果的另一个文件,并处理对飞你的DNA:
如
pattern = 'AAA'
with open('practice_data.txt') as f_dna, open('result.txt', 'w') as f_result:
for line in DNA:
for sequence in line.split():
result = smallest_distance(pattern, sequence)
f_result.write(result)
警告:您将不得不确保您的功能smallest_distance
接受string
而不是list
。
如果不可能,您可能需要处理批处理,但由于它有点复杂,所以我不会在此讨论这个问题。现在
可以使用例如genetor功能,提高可读性
def extract_sequence(file, pattern):
for line in file:
for sequence in line.split():
yield smallest_distance(pattern, sequence)
pattern = 'AAA'
with open('practice_data.txt') as f_dna, open('result.txt', 'w') as f_result:
for result in extract_sequence(f_dna, pattern):
f_result.write(result)
请给practice_data.txt重构了一下。您可以在gist.github.com上发帖,并将链接提供给我们。 –
'for'循环消耗'DNA'。如果你评论它,它不会。这可能会影响'smallest_distance(pattern,DNA)'调用。 – janos
[你可能对这个CodeReview问题感兴趣](https://codereview.stackexchange.com/questions/135217/matlab-implementation-of-needleman-wunsch-algorithm) –