Python基础之字符串、日期、字符练习

发布时间:2026/7/25 17:01:43
Python基础之字符串、日期、字符练习 题目 1字符串与数学计算编写一个函数接收一个由数字组成的字符串例如12345完成以下功能将字符串中的每个字符转为整数存入列表计算列表中所有数字的平均值保留 2 位小数计算列表中所有数字的几何平均数返回平均值、几何平均数几何平均数公式GMx1x2x3...xnnGM \sqrt[n]{x_1x_2x_3...x_n}GMnx1​x2​x3​...xn​​defexam1(nums:str):# 写法一# num_list []# for num in nums:# num_list.append(int(num))# return num_list# 写法二:# num_list list(map(int, nums))# 写法三num_list[int(num)fornuminnums]# 平均数avground(sum(num_list)/len(num_list),2)print(avg)# 几何平均数result1fornuminnum_list:resultresult*num GMround(result**(1/len(num_list)),2)returnavg,GM avg,GMexam1(12345)print(平均数:,avg)print(几何平均数:,GM)题目2综合日期计算编写函数get_mondays(start_date: str, n: int)接收一个起始日期字符串格式YYYY-MM-DD和天数 N完成把字符串转为 datetime 日期对象生成从起始日期开始未来 N 天的所有日期筛选出其中所有周一的日期返回周一日期列表输入start_date2025-01-01, N30 输出[2025-01-06, 2025-01-13, 2025-01-20, 2025-01-27]# 思路一在start_date_obj基础上一次1,2,3,......n,再判断哪些是周一defget_mondays(start_date:str,n:int):start_datedatetime.datetime.strptime(start_date,%Y-%m-%d)print(start_date,start_date)result[]foriinrange(n1):after_datestart_datedatetime.timedelta(daysi)ifafter_date.weekday()0:result.append(after_date.strftime(%Y-%m-%d))returnresultprint((get_mondays(2026-07-25,20)))# 思路二找到第一个周一之后7defget_mondays(start_date:str,n:int)-list:start_datedatetime.datetime.strptime(start_date,%Y-%m-%d)mondays_list[]start_weekstart_date.weekday()# print(start_week)# start_week 0 start_date timedelta(0)# start_week 1 start_date timedelta(6)# start_week 2 start_date timedelta(5)# start_week 3 start_date timedelta(4)# start_week 4 start_date timedelta(3)# start_week 5 start_date timedelta(2)# start_week 6 start_date timedelta(1)start7-start_weekifstart_week!0else0first_mondaystart_datetimedelta(daysstart)foriinrange(start,n,7):everydayfirst_mondaytimedelta(i)mondays_list.append(everyday.strftime(%Y-%m-%d))returnmondays_listprint((get_mondays(2026-07-27,20)))题目3词频统计给定一段英文文本包含大小写、标点完成去掉所有标点符号全部转为小写按单词统计出现次数使用 Counter使用 defaultdict 统计首字母相同的单词列表Hello world! Hello Python. Python is fun, fun fun. Wow!单词频次 {fun: 3, hello: 2, python: 2, world: 1, is: 1, wow: 1} 首字母分组 {w: [wow, world], i: [is], h: [hello], f: [fun], p: [python]}defexam3(sentence:str):# 写法一# for s in string.punctuation:# sentence sentence.replace(s,)# return sentence# 写法二:正则sentencere.sub(r\W, ,sentence)returnsentenceprint(exam3(Hello world! Hello Python. Python is fun, fun fun. Wow!))