简体   繁体   English

从字典打印声明

[英]printing statement from a dictionary

text = 'hello'
vowels = 'aeiou'


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




print(minimum_dict)

How can I make it so this program I wrote prints "vowel x occurs y amount of times". 我该如何写,所以我写的这个程序打印出“元音x出现y次”。

I tried but I can't get it to work properly, the program Is where there is an input of a word and it checks to see the least frequent vowels which occur. 我尝试了一下,但无法使其正常运行,该程序是输入单词的地方,它检查是否出现了最不常见的元音。

You can loop through the dictionary to get the key and value. 您可以遍历字典以获取键和值。 items returns a tuple pair. items返回一个元组对。

Include the part below in your code to print the desired result: 在代码中包含以下部分以打印所需的结果:

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

minimum_dict.items() returns a list of items which have the key into the dictionary and it's associated value : minimum_dict.items()返回具有字典中key及其相关value的项目列表:

value in this case is equivalent to minimum_dict[key] . 在这种情况下, value等于minimum_dict[key]

Your code can be simplified using collections.defaultdict() as: 您可以使用collections.defaultdict()将代码简化为:

>>> 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}

In case you had to store the count of all characters, this code could be further simplified using collections.Counter() as: 如果必须存储所有字符的计数,则可以使用collections.Counter()将代码进一步简化为:

from collections import Counter
Counter(text)
for vowel, occurrences in minimum_dict.items():
    print("vowel", vowel, "occurs ", occurrences, "times")

This will loop through your dictionary of the minimally occurring vowels, and for each vowel/occurrence pair will print the string "vowel", the actual vowel, the string "occurs", the number of occurrences, and the string "times". 这将遍历您最少出现的元音字典,对于每个元音/出现对,将打印字符串“ vowel”,实际元音,字符串“ occurs”,出现次数和字符串“ times”。

The print() function takes any number of unnamed parameters and converts them to strings and then writes them to output. print()函数接受任意数量的未命名参数,并将其转换为字符串,然后将其写入输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM