排序值(for循环)

wom*_*atp 1 python python-2.7

我正在使用python 2.7中的一个简单的核苷酸计数器,在我写的一种方法中,我想打印g,c,a,t值,这些按它们在基因表中显示的次数排序. 什么是更好的方法呢?提前致谢!

 def counting(self):
    gene = open("BRCA1.txt", "r")
    g = 0
    a = 0
    c = 0
    t = 0
    gene.readline()
    for line in gene:
        line = line.lower()
        for char in line:
            if char == "g":
                g += 1
            if char == "a":
                a += 1
            if char == "t":
                t += 1
            if char == "c":
                c += 1
    print "number of g\'s: %r" % str(g)
    print "number of c\'s: %r" % str(c)
    print "number of d\'s: %r" % str(a)
    print "number of t\'s: %r" % str(t)
Run Code Online (Sandbox Code Playgroud)

shx*_*hx2 6

使用Counter类.

from collections import Counter
counter = Counter(char for line in gene for char in line.lower() )
for char, count in counter.most_common():
    print "number of %s\'s: %d" % (char, count)
Run Code Online (Sandbox Code Playgroud)