簡體   English   中英

如何將多個 string.counts 添加到列表中? 我正在嘗試使用元組打印數字

[英]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))

你可以試試這個。

dna_string = 'ATGCTTCAGAAAGGTCTTACG'

print(*[dna_string.count(a) for a in ['A','C','T','G']],sep=" ")

您可以將這些添加到列表中,例如:

combien = [dna_string.count(x) for x in ['A','C','T','G']]

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:

There are 21 letters in this DNA string.
[('A', 6), ('T', 6), ('G', 5), ('C', 4)]

元素在 Counter 中從高計數到低計數排序,如果您想要另一個結果順序,您可以這樣排序:

print(sorted(list(combien.items()), key=lambda x: ["A", "C", "T", "G"].index(x[0])))

Output:

[('A', 6), ('C', 4), ('T', 6), ('G', 5)]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM