从字典打印语句

2024-06-01 06:07:14 发布

您现在位置:Python中文网/ 问答频道 /正文

text = 'hello'
vowels = 'aeiou'


for char in text.lower():
    if char in vowels:




print(minimum_dict)

我怎样才能让我写的这个程序打印出“元音x出现y次”。你知道吗

我试过了,但我不能让它正常工作,该程序是有一个词的输入,它检查,以查看出现频率最低的元音。你知道吗


Tags: textin程序helloforiflowerdict
3条回答

可以使用^{}将代码简化为:

>>> from collections import defaultdict
>>> text = 'hello'
>>> vowels = 'aeiou'
>>> vowel_count = defaultdict(int)
>>> for c in text:
...     if c in vowels:
...         vowel_count[c] += 1
...
>>> vowel_count
{'e': 1, 'o': 1}

如果您必须存储所有字符的计数,则可以使用^{}将此代码进一步简化为:

from collections import Counter
Counter(text)

您可以循环浏览字典以获取键和值。items返回元组对。你知道吗

在代码中包含以下部分以打印所需结果:

for key,value in minimum_dict.items():
    print("Vowel ", key, "occurs", value ," times")

minimum_dict.items()将具有key的项的列表返回到字典中,并与之关联value

在这种情况下value等价于minimum_dict[key]。你知道吗

for vowel, occurrences in minimum_dict.items():
    print("vowel", vowel, "occurs ", occurrences, "times")

这将在最小出现元音的字典中循环,并为每个元音/出现对打印字符串“元音”、实际元音、字符串“出现”、出现次数和字符串“次数”。你知道吗

函数的作用是:获取任意数量的未命名参数并将其转换为字符串,然后将其写入输出。你知道吗

相关问题 更多 >