使用python中的字典计算每个字符的频率

fhity93d  于 2023-02-14  发布在  Python
关注(0)|答案(6)|浏览(163)

我的程序,它接受用户输入的字符串,并使用字典计算每个字符的频率。输入:

Python programming is fun
    • 预期产出:**
{'p': 2, 'y': 1, 't': 1, 'h': 1, 'o': 2, 'n': 3, 'r': 2, 'g': 2, 'a': 1, 'm': 2, 'i': 2, 's': 1, 'f': 1, 'u': 1}

我的代码:

string = input().lower()
dicx = {}
count = 0
for i in string:
    dicx['i'] = ''

print(dicx)
wtzytmuj

wtzytmuj1#

使用集合。计数器

dicx = collections.Counter(string.lower())
mefy6pfw

mefy6pfw2#

你可以遍历string并相应地更新字典,而且不需要任何count变量。

test_str = input().lower()
dicx = {} 
  
for i in test_str: 
    if i in dicx: 
        dicx[i] += 1
    else: 
        dicx[i] = 1

print(dicx)
kmb7vmvb

kmb7vmvb3#

函数将输入作为字符串,计算字符数并将其存储在字典中

from typing import Dict

char_dict = {} #type: Dict[str, int]

def char_count(string: str) -> dict:
    new_string = string.lower()
    for c in new_string:
        if c in char_dict:
            char_dict[c] += 1
        else:
            char_dict[c] = 1
    return char_dict

if __name__ == "__main__":
    UserString = input("Enter Input String: ")
    CharCount = char_count(UserString)
    print("Characters Count: ", CharCount)

示例:

Enter Input String: Python programming is fun

Characters Count:  {'p': 2, 'y': 1, 't': 1, 'h': 1, 'o': 2, 'n': 3, ' ': 3, 'r': 2, 'g': 2, 'a': 1, 'm': 2, 'i': 2, 's': 1, 'f': 1, 'u': 1}
r9f1avp5

r9f1avp54#

方式一:为

symbols = {}
    for s in inp_str.lower():
        if s in symbols:
            symbols[s] += 1
        else:
            symbols.update({s: 1})
    print(symbols)

方式二:默认

symbols = defaultdict(int)
     for s in inp_str.lower():
         symbols[s] += 1
     print(symbols)

方式三:柜台

symbols = Counter(inp_str.lower())
    print(symbols)
ef1yzkbh

ef1yzkbh5#

def charCounter(string):
    empty = {}
    for i in string.lower():
        if i in empty.keys():
            empty[i] += 1
        else:
            empty[i] = 1
    return empty

print(charCounter("Oh, it is python"))
ghhkc1vu

ghhkc1vu6#

d = {}
test_str = input().lower()

for x in test_str:
    d[x] = d.get(x,0) + 1
print(d)

像这样优雅多了

相关问题