案例1:成绩表和平均分统计。

说明:录入5个学生3门课程的考试成绩,计算每个学生的平均分和每门课的平均分。

  1. """
  2. 录入5个学生3门课程的考试成绩
  3. 计算每个学生的平均分和每门课的平均分
  4. """
  5. names = ['关羽', '张飞', '赵云', '马超', '黄忠']
  6. courses = ['骑马', '射箭', '兵器']
  7. # 用生成式创建嵌套的列表保存5个学生3门课程的成绩
  8. scores = [[0] * len(courses) for _ in range(len(names))]
  9. # 录入成绩
  10. for i, name in enumerate(names):
  11. print(f'请输入{name}的成绩--->')
  12. for j, course in enumerate(courses):
  13. scores[i][j] = float(input(f'{course}:'))
  14. print('------')
  15. print('#' * 5, '每个人的平均成绩', '#' * 5)
  16. for i, name in enumerate(names):
  17. average_score = sum(scores[i]) / len(courses)
  18. print(f'{name}的平均成绩是:{average_score:.1f}')
  19. print('#' * 5, '每门课的平均成绩', '#' * 5)
  20. for j, course in enumerate(courses):
  21. course_scores = [score[j] for score in scores]
  22. average_score = sum(course_scores) / len(names)
  23. 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}’)

  1. <a name="gvGBg"></a>
  2. ## 案例2:设计一个函数返回指定日期是这一年的第几天。
  3. > **说明**:这个案例源于著名的> _The C Programming Language_上的例子。
  4. ```python
  5. """
  6. 计算指定的年月日是这一年的第几天
  7. """
  8. def is_leap_year(year):
  9. """
  10. 判断是不是闰年
  11. :param year: 年份
  12. :return: 平年返回False,闰年返回True
  13. """
  14. return year % 4 == 0 and year % 100 != 0 or year % 400 == 0
  15. def which_day(year, month, date):
  16. """
  17. 输入一个日期计算是这一年的第几天
  18. :param year: 年
  19. :param month: 月
  20. :param date: 日
  21. :return: 天数
  22. """
  23. # 存储平年和闰年每个月的天数
  24. days_of_month = [
  25. [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
  26. [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
  27. ]
  28. # 布尔值False和True可以转换成整数0和1,因此
  29. # 平年会选中嵌套列表中的第一个列表(2月是28天)
  30. # 闰年会选中嵌套列表中的第二个列表(2月是29天)
  31. days = days_of_month[is_leap_year(year)]
  32. total = 0
  33. for i in range(month-1):
  34. total += days[i]
  35. return total + date
  36. print(which_day(1980, 11, 28)) # 333
  37. print(which_day(1995, 8, 8)) # 220
  38. print(which_day(2021, 1, 1)) # 1
  39. print(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())

  1. <a name="ADk9Q"></a>
  2. ### 案例4:幸运的女人。
  3. > **说明**:有15个男人和15个女人乘船在海上遇险,为了让一部分人活下来,不得不将其中15个人扔到海里,有个人想了个办法让大家围成一个圈,由某个人开始从1报数,报到9的人就扔到海里面,他后面的人接着从1开始报数,报到9的人继续扔到海里面,直到将15个人扔到海里。最后15个女人都幸免于难,15个男人都被扔到了海里。问这些人最开始是怎么站的,哪些位置是男人,哪些位置是女人。
  4. ```python
  5. """
  6. 幸运的女人(约瑟夫环问题)
  7. """
  8. persons = [True] * 30
  9. # counter - 扔到海里的人数
  10. # index - 访问列表的索引
  11. # number - 报数的数字
  12. counter, index, number = 0, 0, 0
  13. while counter < 15:
  14. if persons[index]:
  15. number += 1 # 报数
  16. if number == 9:
  17. persons[index] = False # 丢海里
  18. counter += 1
  19. number = 0 # 重新报数
  20. index += 1
  21. index %= 30 # 开始下一轮
  22. for person in persons:
  23. print('女' if person else '男', end='')