闲话少数,直接上代码。
#!/usr/bin/python3
#! encoding ='utf-8'
# 需求 3个办公室,随机分配给8位老师
"""
分析:
1.准备数据;
2.分配老师到办公室 --使用遍历列表
3.检验分配结果是否成功
"""
import random # 引入随机模块
# 1. 准备数据
# 1.1 老师数据
teachers = ["a", "b", "c", "d", "e", "f", "g", "h"]
# 1.2 使用使用列表嵌套,准备办公室数据
offices = [[], [], []]
# 2.分配老师到办公室
# 使用for循环遍历语句
for teacher in teachers:
office = random.randint(0, 2) # 随机模块
offices[office].append(teacher) # 列表追加模块
# print(offices)
# 3.检验分配结果,输出打印
num = 1
# 打印办公室人数和人名
for office in offices:
print(f"\n办公室{num}有人数{len(office)},他们分别是:", end="")
for teacher in office:
print(teacher, end="")
num += 1
输出的结果:
输出结果:
办公室1有人数2,他们分别是:ae
办公室2有人数2,他们分别是:cd
办公室3有人数4,他们分别是:bfgh
Process finished with exit code 0
此案例涉及到Python的知识点有:
1.模块引入,import random # 引入随机模块。语法:random.randint(下标开始位置,下标结束位置)
2.列表嵌套,of