简体   繁体   English

如何计算 python 中字母的出现次数?

[英]How to count occurrence of alphabet in python?

I have written a custom python code to count the occurrence of an alphabet after a certain alphabet.我编写了一个自定义 python 代码来计算某个字母表之后出现的字母表。 For example, in my case, I have a string "ABACCD".例如,就我而言,我有一个字符串“ABACCD”。 Now I want to find that starting with alphabet "A", in my string, how many times it is followed by "B", how many times it is followed by "C" etc. Similarly for "B" as well, how many time it is followed by "A", how many time it is followed by "B", how many times it is followed by "C".现在我想找到从字母“A”开始,在我的字符串中,它后面跟着“B”多少次,后面跟着“C”多少次等等。对于“B”也是如此,有多少后面跟“A”的时间,跟“B”的次数,跟“C”的次数。 So the output will be something like: If my alphabet is "A", it is being followed by "A" zero times, it is being followed by "B" 1 time, followed by "C" 1 time and followed by "D" 0 times.因此,output 将类似于:如果我的字母表是“A”,则后面跟着“A”零次,后面跟着“B”1 次,后面跟着“C”1 次,后面跟着“D” “0次。 The code that I have written just return me a list of 1s.我编写的代码只返回一个 1 列表。 Here is my code:这是我的代码:

s = "ABACCD"
a = []

for i in s:
    if(i=="A"):
        for j in s:
            a_count = 0
            if(j=="A"):
                a_count+=1
                a.append(a_count)
print(a)

Any help would be much appreciated.任何帮助将非常感激。 Thanks谢谢

It's better of use a dictionary than a list to keep track of all the pairs of letter occurences最好使用字典而不是列表来跟踪所有出现的字母对

1. Basic Python using dictionary 1.基本Python使用字典

cnts = {}
for a, b in zip(s, s[1:]):
    cnts[(a,b)] = cnts.get((a, b), 0) + 1

print(cnts) # {('A', 'B'): 1, ('B', 'A'): 1, ('A', 'C'): 1, ('C', 'C'): 1, ('C', 'D'): 1}

2. Basic Python without zip 2.基本Python没有zip

cnts = {}
i = 0
while i < len(s) - 1:
    a = s[i]
    b = s[i+1]
    cnts[(a,b)] = cnts.get((a, b), 0) + 1
    i += 1    
print(cnts)
#{('A', 'B'): 1, ('B', 'A'): 1, ('A', 'C'): 1, ('C', 'C'): 1, ('C', 'D'): 1}

3. Solution using collections.Counter 3.使用collections.Counter的解决方案

from collections import Counter
cnts = Counter(zip(s, s[1:]))
print(cnts) 
#Counter({('A', 'B'): 1,
          ('B', 'A'): 1,
          ('A', 'C'): 1,
          ('C', 'C'): 1,
          ('C', 'D'): 1})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM