案例1:成绩表和平均分统计。
说明:录入5个学生3门课程的考试成绩,计算每个学生的平均分和每门课的平均分。
"""录入5个学生3门课程的考试成绩计算每个学生的平均分和每门课的平均分"""names = ['关羽', '张飞', '赵云', '马超', '黄忠']courses = ['骑马', '射箭', '兵器']# 用生成式创建嵌套的列表保存5个学生3门课程的成绩scores = [[0] * len(courses) for _ in range(len(names))]# 录入成绩for i, name in enumerate(names):print(f'请输入{name}的成绩--->')for j, course in enumerate(courses):scores[i][j] = float(input(f'{course}:'))print('------')print('#' * 5, '每个人的平均成绩', '#' * 5)for i, name in enumerate(names):average_score = sum(scores[i]) / len(courses)print(f'{name}的平均成绩是:{average_score:.1f}')print('#' * 5, '每门课的平均成绩', '#' * 5)for j, course in enumerate(courses):course_scores = [score[j] for score in scores]average_score = sum(course_scores) / len(names)print(f'{course}课的平均成绩是:{average_score:.1f}')上面对列表进行遍历的时候,使用了
enumerate函数,这个函数非常有用。我们之前讲过循环遍历列表的两种方法,一种是通过索引循环遍历,一种是直接遍历列表元素。通过enumerate处理后的列表在循环遍历时会取到一个二元组,解包之后第一个值是索引,第二个值是元素,下面是一个简单的对比。 ```python items = [‘Python’, ‘Java’, ‘Go’, ‘Swift’]
for index in range(len(items)): print(f’{index}: {items[index]}’)
for index, item in enumerate(items): print(f’{index}: {item}’)
<a name="gvGBg"></a>## 案例2:设计一个函数返回指定日期是这一年的第几天。> **说明**:这个案例源于著名的> _The C Programming Language_上的例子。```python"""计算指定的年月日是这一年的第几天"""def is_leap_year(year):"""判断是不是闰年:param year: 年份:return: 平年返回False,闰年返回True"""return year % 4 == 0 and year % 100 != 0 or year % 400 == 0def which_day(year, month, date):"""输入一个日期计算是这一年的第几天:param year: 年:param month: 月:param date: 日:return: 天数"""# 存储平年和闰年每个月的天数days_of_month = [[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],[31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]]# 布尔值False和True可以转换成整数0和1,因此# 平年会选中嵌套列表中的第一个列表(2月是28天)# 闰年会选中嵌套列表中的第二个列表(2月是29天)days = days_of_month[is_leap_year(year)]total = 0for i in range(month-1):total += days[i]return total + dateprint(which_day(1980, 11, 28)) # 333print(which_day(1995, 8, 8)) # 220print(which_day(2021, 1, 1)) # 1print(which_day(2021, 7, 16)) # 197
案例3:实现双色球随机选号。
说明:双色球属乐透型彩票范畴,由中国福利彩票发行管理中心统一组织发行,在全国范围内销售。红球号码范围为01~33,蓝球号码范围为01~16。双色球每期从33个红球中开出6个号码,从16个蓝球中开出1个号码作为中奖号码,双色球玩法即是竞猜开奖号码的6个红球号码和1个蓝球号码。 这个题目的思路是用一个列表保存红色球的号码,然后通过
random模块的sample函数实现无放回抽样,这样就可以抽中6个不重复的红色球号码。红色球需要排序,可以使用列表的sort方法,显示的时候一位数前面需要做补0的操作,可以用字符串格式化的方式来处理。 ```python “”” 双色球随机选号 “”” from random import sample, randint
def random_select(): “”” 随机选择一组号码 :return: 号码列表 “”” red_balls = [x for x in range(1, 34)] # 红色球 selected_balls = sample(red_balls, 6) # 不放回抽取6个 selected_balls.sort() # 排序 selected_balls.append(randint(1, 16)) # 随机生成一个蓝色号码 return selected_balls
def display(balls): “””输出列表中的双色球号码””” for index, ball in enumerate(balls): if index == len(balls) - 1: print(‘|’, end=’ ‘) # 分割红色号和蓝色号 print(f’{ball:0>2d}’, end=’ ‘) # 一位数前面补0 print()
n = int(input(‘机选几注: ‘)) for _ in range(n): display(random_select())
<a name="ADk9Q"></a>### 案例4:幸运的女人。> **说明**:有15个男人和15个女人乘船在海上遇险,为了让一部分人活下来,不得不将其中15个人扔到海里,有个人想了个办法让大家围成一个圈,由某个人开始从1报数,报到9的人就扔到海里面,他后面的人接着从1开始报数,报到9的人继续扔到海里面,直到将15个人扔到海里。最后15个女人都幸免于难,15个男人都被扔到了海里。问这些人最开始是怎么站的,哪些位置是男人,哪些位置是女人。```python"""幸运的女人(约瑟夫环问题)"""persons = [True] * 30# counter - 扔到海里的人数# index - 访问列表的索引# number - 报数的数字counter, index, number = 0, 0, 0while counter < 15:if persons[index]:number += 1 # 报数if number == 9:persons[index] = False # 丢海里counter += 1number = 0 # 重新报数index += 1index %= 30 # 开始下一轮for person in persons:print('女' if person else '男', end='')
