在字典中连续存储的单独值
Separate value that store consecutively in dictionary
我目前正在研究 CS50 问题集 https://cs50.harvard.edu/x/2021/psets/6/dna/
题目只是告诉我们在一个txt文件中找到一些连续重复的DNA序列,并将总长度与csv文件中的人相匹配。
这是我目前使用的代码(尚未完成):
import re, csv, sys
def main(argv):
# Open csv file
csv_file = open(sys.argv[1], 'r')
str_person = csv.reader(csv_file)
nucleotide = next(str_person)[1:]
# Open dna sequences file
txt_file = open(sys.argv[2], 'r')
dna_file = txt_file.read()
str_repeat = {}
str_list = find_STRrepeats(str_repeat, nucleotide, dna_file)
def find_STRrepeats(str_list, nucleotide, dna):
for STR in nucleotide:
groups = re.findall(rf'(?:{STR})+', dna)
if len(groups) == 0:
str_list[STR] = 0
else:
str_list[STR] = groups
print(str_list)
if __name__ == "__main__":
main(sys.argv[1:])
输出(from the print(str_list)
):
{'AGATC': ['AGATCAGATCAGATCAGATC'], 'AATG': ['AATG'], 'TATC': ['TATCTATCTATCTATCTATC']}
但是正如你所见,字典中的值也是连续存储的。如果我想在 str_list[STR] = len(groups)
中使用 len 函数,它将为字典中的每个键生成 1。因为我想找出 DNA 重复了多少次(总长度),并将其作为值存储在我的字典中。
所以,我想单独存放。有点像这样:
{'AGATC': ['AGATC', 'AGATC', 'AGATC', 'AGATC'], 'AATG': ['AATG'], 'TATC': ['TATC', 'TATC', 'TATC', 'TATC', 'TATC']}
我应该在我的代码中添加什么,以便它们可以像那样用昏迷分开?或者我可以将某些条件添加到我的 ReGex 代码中 groups = re.findall(rf'(?:{STR})+', dna)
?
我不想更改整个 ReGex 代码。因为我认为找到连续重复的最大长度的字符串已经很有用了。我为自己能够在没有帮助的情况下得到它感到自豪,因为我是 python 的初学者。请。谢谢。
我只存储最高重复次数:
...
if len(groups) == 0:
str_list[STR] = 0
else:
str_list[STR] = max(len(i)/len(str) for i in groups)
....
顺便说一句,这将正确处理存在多个序列的情况。
我目前正在研究 CS50 问题集 https://cs50.harvard.edu/x/2021/psets/6/dna/
题目只是告诉我们在一个txt文件中找到一些连续重复的DNA序列,并将总长度与csv文件中的人相匹配。
这是我目前使用的代码(尚未完成):
import re, csv, sys
def main(argv):
# Open csv file
csv_file = open(sys.argv[1], 'r')
str_person = csv.reader(csv_file)
nucleotide = next(str_person)[1:]
# Open dna sequences file
txt_file = open(sys.argv[2], 'r')
dna_file = txt_file.read()
str_repeat = {}
str_list = find_STRrepeats(str_repeat, nucleotide, dna_file)
def find_STRrepeats(str_list, nucleotide, dna):
for STR in nucleotide:
groups = re.findall(rf'(?:{STR})+', dna)
if len(groups) == 0:
str_list[STR] = 0
else:
str_list[STR] = groups
print(str_list)
if __name__ == "__main__":
main(sys.argv[1:])
输出(from the print(str_list)
):
{'AGATC': ['AGATCAGATCAGATCAGATC'], 'AATG': ['AATG'], 'TATC': ['TATCTATCTATCTATCTATC']}
但是正如你所见,字典中的值也是连续存储的。如果我想在 str_list[STR] = len(groups)
中使用 len 函数,它将为字典中的每个键生成 1。因为我想找出 DNA 重复了多少次(总长度),并将其作为值存储在我的字典中。
所以,我想单独存放。有点像这样:
{'AGATC': ['AGATC', 'AGATC', 'AGATC', 'AGATC'], 'AATG': ['AATG'], 'TATC': ['TATC', 'TATC', 'TATC', 'TATC', 'TATC']}
我应该在我的代码中添加什么,以便它们可以像那样用昏迷分开?或者我可以将某些条件添加到我的 ReGex 代码中 groups = re.findall(rf'(?:{STR})+', dna)
?
我不想更改整个 ReGex 代码。因为我认为找到连续重复的最大长度的字符串已经很有用了。我为自己能够在没有帮助的情况下得到它感到自豪,因为我是 python 的初学者。请。谢谢。
我只存储最高重复次数:
...
if len(groups) == 0:
str_list[STR] = 0
else:
str_list[STR] = max(len(i)/len(str) for i in groups)
....
顺便说一句,这将正确处理存在多个序列的情况。