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)