python—字典练习(统计字符出现频率)

题目一:

数字重复统计:
    1)随机生成1000个整数;
    2)数字范围[20,100];
    3)升序输出所有不同的数字及其每个数字重复的次数

代码:

import random
RandNum = []
for item in range(1000):
    RandNum .append(random.randint(20,100))
Sort_Num = sorted(RandNum)
Num_Dic = {}
for num in Sort_Num:
    if num in Num_Dic:
        Num_Dic[num] += 1
    else:
        Num_Dic[num] = 1
print(Num_Dic)

python—字典练习(统计字符出现频率)

结果:
python—字典练习(统计字符出现频率)

题目二:

重复的单词: 此处认为单词之间以空格为分隔符, 并且不包含,和.;
    # 1. 用户输入一句英文句子;
    # 2. 打印出每个单词及其重复的次数;
 "hello java hello python"
# hello 2
# java 1
# python 1

代码:

Sentence = input('Enter Sentence:')
str = Sentence.split(' ')

WordCount = {}
for num in str:
    if num in WordCount:
        WordCount[num] += 1
    else:
        WordCount[num] = 1
print(WordCount)
for k,v in WordCount.items():
    print(k,'-->',v)

结果:
python—字典练习(统计字符出现频率)