从大括号中删除频率列表以向下列出项目

问题描述 投票:0回答:3

我一直在尝试解决一项任务,要求我编写一个程序来确定字符串中字母的频率。

我制作的东西几乎满足任务要求,但又不完全满足。最后一个元素是列出字母表中的字母以及每个字母在字符串中出现的频率,格式如下:

A: 10
B: 2
C : 1
... etc.

我的解决方案让我达到了这一点:

{'a': 10, 'b': 1, 'c': 2, 'd': 2, 'e': 2, 'f': 2, 'g': 0, 'h': 4, 'i': 6, 'j': 0, 'k': 0, 'l': 0, 'm': 2, 'n': 7, 'o': 9, 'p': 0, 'q': 0, 'r': 2, 's': 0, 't': 10, 'u': 5, 'v': 2, 'w': 2, 'x': 0, 'y': 2, 'z': 0}`

但我无法弄清楚如何从大括号中删除此列表并按上面的方式显示它们。

这是我的代码:

message = "You can have data without information, but you cannot have information without data."
alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q",     "r", "s", "t", "u", "v", "w", "x", "y", "z"]
frequency = { "a": 0, "b": 0, "c": 0, "d": 0, "e": 0, "f": 0, "g": 0, "h": 0, "i": 0, "j": 0,    "k": 0, "l": 0, "m": 0, "n": 0, "o": 0, "p": 0, "q": 0, "r": 0, "s": 0, "t": 0, "u": 0, "v": 0, "w": 0, "x": 0, "y": 0, "z": 0 }

for i in alphabet:
    for j in message.lower():
        if i == j:
            frequency[i] += 1
print(frequency)

产生这个:

{'a': 10, 'b': 1, 'c': 2, 'd': 2, 'e': 2, 'f': 2, 'g': 0, 'h': 4, 'i': 6, 'j': 0, 'k': 0, 'l': 0, 'm': 2, 'n': 7, 'o': 9, 'p': 0, 'q': 0, 'r': 2, 's': 0, 't': 10, 'u': 5, 'v': 2, 'w': 2, 'x': 0, 'y': 2, 'z': 0}

任何人都可以帮助我了解如何将这些结果转换为:

a: 10
b: 1
c: 2
...
python list for-loop frequency
3个回答
0
投票

此代码计算

letter
中的每个
alphabet
在给定字符串中出现的次数,并以
letter
:
number of occurrences

格式显示结果
message = "You can have data without information, but you cannot have information without data."
alphabet = "abcdefghijklmnopqrstuvwxyz"  
frequency = {char: 0 for char in alphabet}
for char in message.lower():
    if char in frequency:
        frequency[char] += 1
for char in alphabet:
    print(f"{char}: {frequency[char]}")

0
投票

实际上非常简单,只需使用字典的 items 方法即可返回键值对元组。

alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
frequency = {letter: 0 for letter in alphabet} # you can use for clause comprehension to initialize the letters. 

message = message.lower()

for char in message:
    if char in frequency:
        frequency[char] += 1

for letter, count in frequency.items():  # use items method then unpack the tuple.
    print(f"{letter.upper()}: {count}") 

0
投票

与许多类似的挑战一样,有多种方法可以实现您的目标。

您可能应该使用 collections 模块中的 Counter 类:

message = "You can have data without information, but you cannot have information without data."
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

counter = Counter(message.upper())

for c in alphabet:
    print(f"{c}: {counter.get(c, 0)}")

输出:

A: 10
B: 1
C: 2
D: 2
E: 2
F: 2
G: 0
H: 4
I: 6
J: 0
K: 0
L: 0
M: 2
N: 7
O: 9
P: 0
Q: 0
R: 2
S: 0
T: 10
U: 5
V: 2
W: 2
X: 0
Y: 2
Z: 0
© www.soinside.com 2019 - 2024. All rights reserved.