Question:3个办公室,8个老师(a,b,c,d,e,f,g,h),把8个老师随机分配到3个办公室,并打印出来
import random ''' 解法①: my_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] office_1 = [] office_2 = [] office_3 = [] for number in range(len(my_list)): y = random.randint(1, 3) if y == 1: office_1.append(my_list[number - 1]) elif y == 2: office_2.append(my_list[number - 1]) else: office_3.append(my_list[number - 1]) print('第一个办公室的老师有:',office_1) print('第二个办公室的老师有:',office_2) print('第三个办公室的老师有:',office_3) ''' ''' 解法②: offices = [[], [], []] names = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] for name in names: index = random.randint(0, 2) offices[index].append(name) i = 1 for office in offices: print('办公室%d的人数为:%d'%(i, len(office))) print('成员有:',end='\t') for name in office: print('%s'%name, end='\t') print('\n') print('——'*10) i += 1 ''' 盲区: 1、给列表office编码 → 放到另一个列表里,即嵌套 2、循环:'for i in 列表:' 3、+= 4、一个问题不一定就只能用一个大的综合的循环解决 '''