每次循环迭代都创建一个新字典

Create a new dictionary with each iteration of loop

我正在尝试从 VCF 文件中提取位置和 SNP。到目前为止,我已经写了以下内容。但是我怎样才能更改字典的名称,以便最终为每个输入文件得到一个字典?

即:python vcf_compare.py file1.vcf file2.vcf file3.vcf

import sys

import vcf

for variants in sys.argv[1:]:
    file1 = {} 
    vcf_reader = vcf.Reader(open(variants))
    for record in vcf_reader:
        pos = record.POS
        alt = record.ALT
        ref= record.REF
        snps[pos]=ref,alt

因此为 argv[1] 创建了一个名为 file1 的字典。我怎样才能使字典更改名称为例如文件二用于循环的第二次迭代?

你应该使用 collections.defaultdict 也应该使用 with open(...):

from collections import defaultdict

files = defaultdict(dict)
for filename in sys.argv[1:]:
    with open(filename) as f:
        vcf_reader = vcf.Reader(f)
        for record in vcf_reader:
            files[filename][record.POS] = record.REF, record.ALT

所有这些不错的 python 技巧使代码更易读,更短,使用更少的中间临时变量。此外,使用 with open() 可确保每个文件在读取后自动关闭。

此外,如您所见,您可以选择更好的变量名,并且还可以大大减少代码行数。

简答:你不能。对于许多早期程序员来说,这是一个令人难以置信的令人沮丧的事实。修复:另一本字典!在 variants for 循环之外,创建另一个字典并使用文件名作为键。示例(你不能只复制粘贴这个,因为我不知道如何使用 vcf 库):

import sys

import vcf

all_files = {}
for variants in sys.argv[1:]:
    #didn't see file1 used, and didn't see snps created
    #so figured file1 was snps...
    snps = {} 
    vcf_reader = vcf.Reader(open(variants))
    for record in vcf_reader:
        pos = record.POS
        alt = record.ALT
        ref= record.REF
        snps[pos]=ref,alt
    all_files[variants] = snps

我在这里假设 variants 是字符串形式的文件名。如果不是,请将 all_files[variants] 中的 variants 替换为您要用作其键的字符串。