[英]Find count of identical adjacent characters in a string
我有一個字符串:'AAAAATTT'
我想編寫一個程序,每當2個值相同時就進行計數。 因此,在“ AAAAATTT”中,其計數為:
AA:4 TT:2
您可以為此使用collections.defaultdict
。 這是O(n)復雜度解決方案,它遍歷相鄰字母並根據條件構建字典。
您的輸出將是一個字典,其中的鍵是重復的字母,而值是計數。
使用itertools.islice
是為了避免為zip
的第二個參數構建新列表。
from collections import defaultdict
from itertools import islice
x = 'AAAAATTT'
d = defaultdict(int)
for i, j in zip(x, islice(x, 1, None)):
if i == j:
d[i+j] += 1
結果:
print(d)
defaultdict(<class 'int'>, {'AA': 4, 'TT': 2}
您可以使用Counter
:
from collections import Counter
s = 'AAAAATTT'
print([(k*2, v - 1) for k, v in Counter(list(s)).items() if v > 1])
#output: [('AA', 4), ('TT', 2)]
您可以將具有字典理解和zip
collections.Counter
用作:
>>> from collections import Counter
>>> s = 'AAAAATTT'
>>> {k: v for k, v in Counter(zip(s, s[1:])).items() if k[0]==k[1]}
{('A', 'A'): 4, ('T', 'T'): 2}
這是使用itertools.groupby
實現此目的的另一種方法,但是它不如上述解決方案那么干凈(在性能方面也會很慢) 。
>>> from itertools import groupby
>>> {x[0]:len(x) for i,j in groupby(zip(s, s[1:]), lambda y: y[0]==y[1]) for x in (tuple(j),) if i}
{('A', 'A'): 4, ('T', 'T'): 2}
一種方法可以如下使用Counter
:
from collections import Counter
string = 'AAAAATTT'
result = dict(Counter(s1+s2 for s1, s2 in zip(string, string[1:]) if s1==s2))
print(result)
結果:
{'AA': 4, 'TT': 2}
您可以使用range
方法嘗試它,而無需導入任何東西:
data='AAAAATTT'
count_dict={}
for i in range(0,len(data),1):
data_x=data[i:i+2]
if len(data_x)>1:
if data_x[0] == data_x[1]:
if data_x not in count_dict:
count_dict[data_x] = 1
else:
count_dict[data_x] += 1
print(count_dict)
輸出:
{'TT': 2, 'AA': 4}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.