简体   繁体   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))

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.

相关问题 我正在尝试获取我打印的内容并将其添加到列表中以作为员工工资单打印出来 - I'm trying to get what I print and add it to a list to print out as an employee payroll 我怎样才能做到这一点? 我正在尝试使用 python 按顺序打印所有数字的输入 - how can i achieve this ? I'm trying to have an Input that will print out all the numbers in sequential order using python 如何打印两个数字的公因数列表? - How do I print out a list of common factors for two numbers? 我正在尝试将数字放入列表并平方并全部打印出来 - I'm trying to put numbers into a list and square and print them all 我正在尝试在多个文件中搜索字符串并在另一个文件中将其打印出来 - I m trying to search a string in multiple files and print them out in another file 如何将已迭代到列表中的数字添加到字符串中? - How do I add numbers I've iterated into a list to a string? 如何垂直打印数字列表? - How do I print a list of numbers vertically? 我试图弄清楚如何添加到字典列表中,而不是创建一个字典列表列表 - I'm trying to figure out how to add to a list of dictionaries, rather than create a list of lists of dictionaries 如何在计算数字后添加一个 int 和一个 str 以打印出来? 我一直在尝试,它不起作用? - How to add a int and a str to print out after it calculates the numbers? I keep trying and it doesnt work? 如何仅在多字符串输入中添加负数? - How do I only add the negative numbers in a multiple string input?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM