1.题目:统计一篇英文文章中每个单词出现的次数,并按照出现次数排序输出。
示例输入:
text = "Python is an interpreted, high-level, general-purpose programming language. Created by Guido van Rossum and first released in 1991, Python's design philosophy emphasizes code readability with its notable use of significant whitespace. Its language constructs and object-oriented approach aim to help programmers write clear, logical code for small and large-scale projects."
示例输出:
[('and', 2), ('code', 2), ('Python', 2), ('its', 2), ('an', 1), ('interpreted,', 1), ('high-level,', 1), ('general-purpose', 1), ('programming', 1), ('language.', 1), ('Created', 1), ('by', 1), ('Guido', 1), ('van', 1), ('Rossum', 1), ('first', 1), ('released', 1), ("Python's", 1), ('design', 1), ('philosophy', 1), ('emphasizes', 1), ('readability', 1), ('with', 1), ('notable', 1), ('use', 1), ('of', 1), ('significant', 1), ('whitespace.', 1), ('Its', 1), ('language', 1), ('constructs', 1), ('object-oriented', 1), ('approach', 1), ('aim', 1), ('to', 1), ('help', 1), ('programmers', 1), ('write', 1), ('clear,', 1), ('logical', 1), ('for', 1), ('small', 1), ('large-scale', 1), ('projects.', 1)]
text = ("Python is an interpreted, is a high-level, general-purpose programming language. Created by Guido van Rossum and first released in 1991")
#将文本转换为小写,并且将标点符号转换为空格
str1=text.lower()
str1=text.replace(',',' ')
str1=text.replace('.',' ')
#将文本按照空格分隔成为单词列表
list1=str1.split(' ')
#统计每个单词出现的次数
dict1={}
for zimu in list1:
if zimu in dict1:
dict1[zimu]+=1
else:
dict1[zimu]=1
#按照出现的次数排序
先将字典转化成有序序列
print(sorted(dict1.items(),key=lambda x:x[1],reverse=True))
2.题目:某小区有3栋楼房,每栋楼房有5个住户,每个住户的姓名、电话号码和房间号都不同,请编写程序将这些信息存储在适当的组合数据类型中,并输出每栋楼房的住户信息。
building_1 = [
["张三", 11111111, 101],
["李四", 11111112, 102],
["王五", 11111113, 103],
["赵六", 11111114, 104],
["孙七", 11111115, 105]
]
building_2 = [
["周八", 22222221, 201],
["吴九", 22222222, 202],
["郑十", 22222223, 203],
["王十一", 22222224, 204],
["李十二", 22222225, 205]
]
building_3 = [
["张十三", 33333331, 301],
["刘十四", 33333332, 302],
["陈十五", 33333333, 303],
["杨十六", 33333334, 304],
["黄十七", 33333335, 305]
]
dict1 = {"1号楼": building_1,"2号楼": building_2,"3号楼": building_3
}
for building_name, residents in dict1.items():
#每个键是一个列表,依次取出每个键,即列表
print(f"{building_name} 的住户信息:")
# 遍历每栋楼中的住户
for resident in residents:
name, phone, room = resident
print(f"姓名: {name}, 电话号码: {phone}, 房间号: {room}")
print()
3.题目:计算一组数据的频率分布,在统计学中,频率分布是一种描述一组数据分布情况的方法。它将数据按照数值大小分成若干个区间,然后统计每个区间内数据的个数,最后绘制成柱状图或直方图。现在给定一组数据,需要编写程序计算它的频率分布。给定一组数据,例如:
data = [3, 1, 4, 2, 5, 3, 2, 3]
输出样式:
区间 频数 频率
0-1 1 0.125
1-2 2 0.25
2-3 3 0.375
3-4 1 0.125
4-5 1 0.125
5-6 0 0.0
data = [3, 1, 4, 2, 5, 3, 2, 3]
total = len(data)
max_val = max(data)
min_val = min(data)
#算出data区间的范围
h = max_val - min_val + 1
#给出一个空的字典用于比较
dict1 = {}
for num in data:
if num in dict1:
dict1[num] += 1
else:
dict1[num] = 1
print(dict1)
# {3: 3, 1: 1, 4: 1, 2: 2, 5: 1}
print("区间 频数 频率")
#区间
for i in range(h): # h的范围从0-4
left = min_val + i
right = left + 1
#count 频率即要获得字典dict1里的value
#字典.get(键,提示信息),根据键获得对应的值
count = dict1.get(left, 0)
f = count / total
print(f"{left}-{right} {count} {f}")
4.题目:学生成绩管理系统
现有学生成绩数据如下(以字符串形式提供),需要对数据进行处理并输出指定统计信息:
data="""
张三,20210001,数学:85,语文:90,英语:88
李四,20210002,数学:78,语文:85,英语:92,编程:88
王五,20210003,数学:92,语文:88,英语:85,编程:95,数据库:89
赵六,20210002,数学:88,语文:82,英语:89,编程:85
周七,20210004,数学:75,语文:80,英语:85
"""# 注意:学号重复(模拟数据错误)
要求:
数据清洗与存储
- 将每行数据按逗号分割,处理为字典结构,键为学号(需去重,后出现的重复学号覆盖之前的)。
- 每个学号对应的 value 是一个字典,包含:
- 姓名(字符串)
- 课程成绩(列表,元素为元组 (课程名, 成绩),例如 ("数学", 85))
统计功能
- 计算每个学生的平均分(保留两位小数),并将结果存入学生字典的 平均分 字段。
- 统计所有课程的选修人数(使用集合去重课程名,避免同一学生重复选修同一课程)。
- 找出每门课程的最高分及其对应的学生姓名(可能有多个学生并列最高分)。
输出结果
- 打印每个学生的完整信息(姓名、学号、课程成绩、平均分)。
- 打印课程统计信息:课程名、选修人数、最高分、最高分学生列表。
data = """
张三,20210001,数学:85,语文:90,英语:88
李四,20210002,数学:78,语文:85,英语:92,编程:88
王五,20210003,数学:92,语文:88,英语:85,编程:95,数据库:89
赵六,20210002,数学:88,语文:82,英语:89,编程:85
周七,20210004,数学:75,语文:80,英语:85
"""
#分析可知应该是两个字
students = {} # 外层字典,学号为键
course_stats = {} # 课程统计字典,键为课程名
# 1. 数据清洗与存储
# splitlines():该方法专门用于按行分割字符串,它能识别多种行分隔符,像 \n、\r、\r\n 等,且无需手动指定分隔符。
for line in data.strip().splitlines():
parts = [p.strip() for p in line.split(',')]
name, sid = parts[0], parts[1]
scores_part = parts[2:]
# 处理课程成绩:分割为 (课程名, 成绩) 元组列表
scores = []
for item in scores_part:
course, score = item.split(':')
scores.append((course, int(score))) # 成绩转为整数
# 去重学号(后出现的覆盖之前的)
students[sid] = {
'姓名': name,
'课程成绩': scores,
'平均分': 0.0 # 后续计算
}
# 2. 计算每个学生的平均分
for sid, student in students.items():
total = sum(score for _, score in student['课程成绩'])
avg = total / len(student['课程成绩'])
student['平均分'] = round(avg, 2) # 保留两位小数
# 3. 统计课程信息(选修人数、最高分、最高分学生)
for sid, student in students.items():
name = student['姓名']
for course, score in student['课程成绩']:
# 初始化课程统计
if course not in course_stats:
course_stats[course] = {
'选修人数': 0,
'最高分': -1,
'最高分学生': []
}
course_stat = course_stats[course]
# 统计选修人数(每个学生每门课程只算一次,即使重复出现也不重复计数)
course_stat['选修人数'] += 1
# 更新最高分及对应学生
if score > course_stat['最高分']:
course_stat['最高分'] = score
course_stat['最高分学生'] = [name]
elif score == course_stat['最高分']:
course_stat['最高分学生'].append(name)
# 4. 打印结果(学生信息)
print("=== 学生信息 ===")
for sid, student in students.items():
print(f"学号:{sid},姓名:{student['姓名']}")
print(f"课程成绩:{student['课程成绩']}")
print(f"平均分:{student['平均分']:.2f}")
print("-" * 30)
# 5. 打印结果(课程统计)
print("\n=== 课程统计 ===")
for course, stat in course_stats.items():
print(f"课程:{course}")
print(f"选修人数:{stat['选修人数']}")
print(f"最高分:{stat['最高分']}")
print(f"最高分学生:{', '.join(stat['最高分学生'])}")
print("-" * 30)