计算每个符号在字符串中出现的次数-python

时间:2019-05-26 04:29:17

标签: python python-3.x count symbols

在此问题中,将为您提供一个代表DNA字符串的字符串s。字符串s由符号“ A”,“ C”,“ G”和“ T”组成。长度为21的DNA字符串的一个示例是“ ATGCTTCAGAAAAAAGGTCTTACG”。

您的任务是编写一个代码,该代码将计算s中每个符号“ A”,“ C”,“ G”和“ T”出现的次数。您的代码应生成4个整数的列表并打印出来。

# Here is the DNA string:
    s = 'AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC'
    # Type your code here

我写错了字符串,字母之间有空格。

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

2 个答案:

答案 0 :(得分:2)

您正在尝试执行collections.Counter的操作:

from collections import Counter

s = 'AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC'

print(Counter(s))

从那里获取计数列表,请使用:

Counter(s).values()

答案 1 :(得分:0)

您基本上处在正确的轨道上,但是无需拆分字符串,因为Python已经为您提供了遍历字符串中每个字符的功能。

您的尝试的修改版本为:

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)