[英]How do I add multiple string.counts into a list? I'm trying to print the numbers out using tuples
dna_string = 'ATGCTTCAGAAAGGTCTTACG'
length = len(dna_string)
print("There are %d letters in this DNA string." % length)
print('Now here are the amounts for the letters "A", "C", "T", "G" in order.\n')
combien_a = dna_string.count('A')
combien_c = dna_string.count('C')
combien_t = dna_string.count('T')
combien_g = dna_string.count('G')
print(str(combien_a) + ' ' + str(combien_c) + ' ' + str(combien_g) + ' ' + str(combien_t))
you can try this.你可以试试这个。
dna_string = 'ATGCTTCAGAAAGGTCTTACG'
print(*[dna_string.count(a) for a in ['A','C','T','G']],sep=" ")
You can add these to a list like:您可以将这些添加到列表中,例如:
combien = [dna_string.count(x) for x in ['A','C','T','G']]
collections.Counter is useful for counting numbers. collections.Counter 可用于计数。
from collections import Counter
dna_string = 'ATGCTTCAGAAAGGTCTTACG'
# Counter object works like a dictionary with element as key and count as value
combien = Counter(dna_string)
print(f"There are {len(dna_string)} letters in this DNA string.")
# you can convert the Counter to a list of (elem, count) tuples
print(list(combien.items())
Output: Output:
There are 21 letters in this DNA string.
[('A', 6), ('T', 6), ('G', 5), ('C', 4)]
Elements are ordered from higher count to lower count in Counter, if you want another order for the result you may sort like this:元素在 Counter 中从高计数到低计数排序,如果您想要另一个结果顺序,您可以这样排序:
print(sorted(list(combien.items()), key=lambda x: ["A", "C", "T", "G"].index(x[0])))
Output: Output:
[('A', 6), ('C', 4), ('T', 6), ('G', 5)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.