簡體   English   中英

計算單個字符串中 char 的出現次數

[英]Count occurrences of char in a single string

string = input(" ")
count = string.count()
print(string + str(count))

需要使用for循環來獲取output:ll2a1m1a1

使用itertools中的groupby

>>> from itertools import groupby
>>> s = 'llama'
>>> [[k, len(list(g))] for k, g in groupby(s)]
[['l', 2], ['a', 1], ['m', 1], ['a', 1]]

如果您確實想要您詢問的 output ,請嘗試以下操作,並按照@DanielMesejo 的建議,使用sum(1 for _ in g)而不是len(list(g))

>>> from itertools import groupby
>>> s = 'llama'
>> groups = [[k, sum(1 for _ in g)] for k, g in groupby(s)]
>>> ''.join(f'{a * b}{b}' for a, b in groups)
'll2a1m1a1'

這適用於您想要的任何單詞,假設這個詞是“發生”,所以

>>> from itertools import groupby
>>> s = 'happen'
>> groups = [[k, sum(1 for _ in g)] for k, g in groupby(s)]
>>> ''.join(f'{a * b}{b}' for a, b in groups)
'h1a1pp2e1n1'

看,你必須解釋更多,這會循環並計算每個字母的次數並將其打印出來。

greeting = 'llama'
for i in range(0, len(greeting)):
    #start count at 1 for original instance.
    count = 1
    for k in range(0, len(greeting)):
        # check letters are not the same position letter.
        if not k == i:
            #check if letters match
            if greeting[i] == greeting[k]:
                count += 1
    print(greeting[i] + str(count))

更基本的方法:

string = 'llama'

def get_count_str(s): 
    previous = s[0]
    for c in s[1:]:
        if c != previous:
            yield f'{previous}{len(previous)}'
            previous = c
        else:
            previous += c


    # yield last
    yield f'{previous}{len(previous)}'

print(*get_count_str(string ), sep='')

output:

ll2a1m1a1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM