[英]Count the number of times each of the symbols appears in a string - python
In this question, you are given a string s which represents a DNA string. 在这个问题中,你会得到一个代表DNA字符串的字符串s。 The string s consists of symbols 'A', 'C', 'G', and 'T'. 字符串s由符号“A”,“C”,“G”和“T”组成。 An example of a length 21 DNA string is "ATGCTTCAGAAAGGTCTTACG." 长度为21的DNA链的一个例子是“ATGCTTCAGAAAGGTCTTACG”。
Your task is to write a code which will count the number of times each of the symbols 'A', 'C', 'G', and 'T' occur in s. 您的任务是编写一个代码,该代码将计算每个符号“A”,“C”,“G”和“T”出现在s中的次数。 Your code should generate a list of 4 integers and print it out. 您的代码应该生成一个包含4个整数的列表并将其打印出来。
# Here is the DNA string:
s = 'AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC'
# Type your code here
Incorrectly, I wrote the string with spaces between letters. 不正确的是,我用字母之间的空格写了字符串。
s='A G C T T T T C A T T C T G A C T G C A A C G G G C A A T A T G T C T C T G T G T G G A T T A A A A A A A G A G T G T C T G A T A G C A G C'
list_of_symbols=s.split(sep=' ')
list_of_symbols
word_count_dictionary={}
for A in list_of_symbols:
if A not in word_count_dictionary:
word_count_dictionary[A]=1
else:
word_count_dictionary[A]+=1
You are trying to do what collections.Counter
does: 你正在尝试做什么collections.Counter
做:
from collections import Counter
s = 'AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC'
print(Counter(s))
From there to get list of counts, use: 从那里获取计数列表,使用:
Counter(s).values()
You are basically on the right track but there's no need to split the string since Python already offers you the ability to loop through each character of the string. 你基本上是在正确的轨道,但没有必要拆分字符串,因为Python已经提供了循环字符串的每个字符的能力。
A modified version of your attempt would be: 您尝试的修改版本将是:
s = 'AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC'
word_count_dictionary = {}
for c in s:
if c not in word_count_dictionary:
word_count_dictionary[c] = 1
else:
word_count_dictionary[c] += 1
print(word_count_dictionary)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.