闲话少数,直接上代码。
#!/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.列表嵌套,office = [[], [], []]。语法:列表 = [[], [], [] ]
3.for列表循环遍历,for 数据 in 列表:
条件语句1……
条件语句2……
4.列表追加,语法:列表.append(数据)
5.字符串的使用,\n: 转行, end = "" :不转行,字符输出:f"字符串{数据}"
6.运算符: num +=1 等于num = num +1
上面用的是列表for循环遍历,下面这个用的是列表while循环遍历
#!/usr/bin/python3
#! encoding ='utf-8'
# 需求 3个办公室,随机分配给8位老师,每个办公室不少于2人
"""
分析:
1.准备数据;
2.分配老师到办公室 --使用遍历列表
3.检验分配结果是否成功
"""
import random # 引入随机模块
# 1. 准备数据
# 1.1 老师数据
teachers = ["a", "b", "c", "d", "e", "f", "g", "h"]
# 1.2 使用使用列表嵌套,准备办公室数据
offices = [[], [], []]
# 2.分配老师到办公室
# 使用While语句
i = 0
while i < len(teachers):
teacher = teachers[i]
i += 1
# print(teacher)
office = random.randint(0, 2)
offices[office].append(teacher)
# print(offices)
# # print(type(office))
# print(len(offices[1]))
# 3.检验分配结果,输出打印
# 打印办公室人数和人名
k = 1
j = 0
office1 = [offices[0].copy(), offices[1].copy(), offices[2].copy()]
# [a1, a2, a3] = [offices[0].copy(), offices[1].copy(), offices[2].copy()]
# office1 = [a1, a2, a3]
while k <= len(offices):
print(f"办公室{k}有{len(office1[j])}人,分别是:")
print(office1[j])
j += 1
k += 1
输出的结果是:
输出的结果:
办公室1有2人,分别是:
['a', 'f']
办公室2有3人,分别是:
['d', 'g', 'h']
办公室3有3人,分别是:
['b', 'c', 'e']
Process finished with exit code 0