【问题标题】:Creating a dictionary to count the number of occurrences of Sequence IDs创建一个字典来计算序列 ID 的出现次数
【发布时间】:2016-07-27 02:50:10
【问题描述】:

我正在尝试编写一个函数来计算此文件中出现的每个序列 ID 的数量(这是一个示例爆炸文件)

上图是我正在处理的输入文件。

def count_seq(input):
    dic1={}
    count=0
    for line in input:
        if line.startswith('#'):
        continue
    if line.find('hits found'):
        line=line.split('\t')
        if line[1] in dic1:
            dic1[line]+=1
        else:
            dic1[line]=1
return dic1

上面是我的代码,调用时只返回空括号 {}

所以我试图计算每个序列 ID(最后 13 行的第二个元素)出现了多少次,例如:FO203510.1 出现 4 次。

任何帮助将不胜感激,谢谢!

【问题讨论】:

  • 这里的文字比图片更受欢迎。人们喜欢复制/粘贴并在您的数据上测试他们的解决方案。
  • 哦,对了,谢谢你让我知道,我没想到也没有意识到这会是个问题!

标签: python-3.x dictionary counting


【解决方案1】:

也许这就是你所追求的:

def count_seq(input_file):
    dic1={}
    with open(input_file, "r") as f:
        for line in f:
            line = line.strip()
            if not line.startswith('#'):
                line = line.split()
                seq_id = line[1]
                if not seq_id in dic1:
                    dic1[seq_id] = 1
                else:
                    dic1[seq_id] += 1

    return dic1

print(count_seq("blast_file"))

【讨论】:

  • 这就是我想要做的,谢谢!仍然对循环和字典感到困惑!
【解决方案2】:

这是 collections.defaultdict 的合适案例。让f 成为文件对象。假设序列在第二列,则只有几行代码。

from collections import defaultdict
d = defaultdict(int)
seqs = (line.split()[1] for line in f if not line.strip().startswith("#"))
for seq in seqs:
    d[seq] += 1

看看有没有用!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-23
    • 2022-11-04
    • 2021-08-21
    • 2021-12-04
    • 1970-01-01
    • 2023-02-26
    • 2019-07-13
    相关资源
    最近更新 更多