[Python]创建for循环,想要创建字典

2024-04-29 06:04:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图通过一个for循环来创建一个字典,在这个循环中它会有一个细菌的描述,关键是它的DNA序列。唯一的问题是,我的变量不能存储多个数据集,它只会覆盖第一个数据集,因此只为字典提供一个输出。你知道吗

#reads a fasta file and seperates the description and dna sequences
for line in resistance_read:
    if line.startswith(">"):
        description = line
    else: 
        sequence = line

#trying to get the output from the for loop and into the dictionary
bacteria_dict = {description:sequence}

输出:

line3description
dna3sequence

但是,通过下面的代码,我可以得到所有的输出

for line in resistance_read:
    if line.startswith(">"):
       print line
    else: 
       print line

输出:

line1description
line2description
line3description
dna1sequence
dna2sequence
dna3sequence

Tags: andthe数据inforreadif字典
2条回答

您在迭代中不断地覆盖变量的值。sequencedescription仅在迭代完成时保存最后的值。你知道吗

相反,首先创建dictionary并将其添加到dictionary中,作为一个更复杂的数据结构,dictionary可以容纳更多的数据。你知道吗


然而,有一个更简单的方法。。。你知道吗

首先,您需要打开文件并读取行。为此,可以使用^{} context manager

with open('file_path', 'r') as f:
    # used strip() to remove '\n'
    lines = [line.strip() for line in f]

现在所有的行都在一个名为lines的列表中,您需要在描述和序列之间创建一个映射。你知道吗

如果描述行正好位于序列行上方,请使用slicing

# take every other line (intervals of 2) starting from index 0
descriptions = lines[0::2]
sequences = lines[0::2]

现在使用^{}将它们压缩在一起,并从每一对创建映射:

result = dict(zip(descriptions, sequences))

如果是另一种情况,你可以使用这个相反的方法:

result = dict(zip(lines[1::2], lines[0::2]))

编辑:

在更新之后,假设每个序列都有一个描述(准确地说),那么这样做的方法似乎是将行列表拆分为一半,然后压缩:

middle = len(lines) / 2
result = dict(zip(lines[:mid], lines[mid:]))

根据你给我们看的例子,你的文件格式是N行描述,然后是N行DNA序列。这个答案假设每个描述或DNA序列都是一行,并且序列和描述一样多。你知道吗

如果你能轻松地把所有的东西都放在记忆中,那么我能想到的最简单的方法就是按照上面Reut Sharabani的建议开始:

with open('file_path', 'r') as f:
    # used strip() to remove '\n'
    lines = [line.strip() for line in f]

一旦有了lines,就很容易创建两个列表,将它们压缩,然后创建一个dict

descriptions = [line for line in lines if line.startswith('>')]
sequences = [line for line in lines if not line.startswith('>')]
result = dict(zip(sequences, descriptions))

但是,如果文件非常大,并且您不想将其整个长度读取四次,那么您只能通过存储描述并在序列出现时将其与序列匹配来处理一次。你知道吗

result = {}
descriptions = []
with open('file_path', 'r') as f:

    line = f.readline().strip()

    while line.startswith('>'):
        descriptions.append(line)
        line = f.readline().strip()

    result[line] = descriptions.pop(0)
    for line in f:
        result[line] = descriptions.pop(0)

当然,如果:

  • 序列的数目与描述的数目并不完全相同
  • 序列与描述的顺序不同
  • 序列和描述不是在整体块中。你知道吗

相关问题 更多 >