9 随机分配工位的案例
# 需求:3个办公室,8个老师待分配工位,完成随机分配。
# 每个办公室都是1个列表
# 老师是一个列表
# 取出老师的下标分到办公室列表
import random
office_list = [[], [], []]
teacher_list = ['牛老师', '张老师', '花老师', '朱老师', '何老师', '刘妍']
while True:
for teacher in teacher_list:
# 随机产生办公室下标
index = random.randint(0, 2)
# 根据办公室下标,获取到指定的某个办公室,为该办公室添加对应的老师
current_office = office_list[index]
current_office.append(teacher)
# office_list[index].append(teacher)
# 解决列表为空的问题
if len(office_list[0]) ==0 or len(office_list[1]) ==0 or len(office_list[2]) ==0:
# 把office_list重新置空
office_list = [[], [], []]
continue
else:
break
print(office_list)
# 遍历办公室列表,获取每一个办公室
count = 1
for office in office_list:
# print(office)
# 获取每个办公室的人数
num = len(office)
print('第%d办公室人数为%d人:' % (count, num))
# 遍历小列表office获取每一位老师
for teacher in office:
print(teacher)
count += 1
结果很随机。
8 列表的嵌套
一个列表重的元素又是一个列表,就是列表的嵌套。
my_list = ['1', '-2', '3', '-4', '0']
# 定义一个变量,存储城市信息,南方城市是一个组,北方城市是一组
city_list = [['广州', '深圳', '上海'], ['北京', '西安', '山东']]
print(city_list)
# 获取北京
# 先获取北京所在列表,根据北京所在列表获取北京数据
north_list = city_list[1]
print(north_list)
result = north_list[0]
print(result)
city_name = city_list[1][0]
print(city_name)
city_name = city_list[0][2]
print(city_name)
# 在北方城市列表重增加天津
# 获取北方城市列表
# 给列表增加城
city_list[1].append('天津')
print(city_list)
结果
[['广州', '深圳', '上海'], ['北京', '西安', '山东']]
['北京', '西安', '山东']
北京
北京
上海
[['广州', '深圳', '上海'], ['北京', '西安', '山东', '天津']]
7 列表的操作
7.6 列表排序和反转(sort,reverse)
sort是将list按照特定的顺序重新排列,默认为从小到大,参数reverse可以改为倒序。
reverse是将list逆置。
数据类型统一后排序。
主要针对数字。
mysql sql进行更强大的排序。
my_list = ['1', '-2', '3', '-4', '0']
# sort调用后不会提供返回值,排序好的数据依然会放到之前的列表里面
print('前:', my_list)
my_list.sort()
print('后 :', my_list)
my_list.reverse()
print('反转:', my_list)
# 先排序,再反转数据
# 此时是降序
my_list.sort(reverse=True)
print('排序后:', my_list)
结果
前: ['1', '-2', '3', '-4', '0']
后 : ['-2', '-4', '0', '1', '3']
反转: ['3', '1', '0', '-4', '-2']
排序后: ['3', '1', '0', '-4', '-2']
7.5 查找元素(index, count)
name_list = ['1', '2', '3', '4', '5']
# 要查找的数据
# 开始下标
# 结束下标
# 返回的指定数据对应下标
index = name_list.index('1')
print(index)
result = name_list.index('2', 0, 3)
print(result)
# count 统计数据出现的次数
value = name_list.count('3')
print(value)
结果
0
1
1
7.4 查找元素(in, not in)
在删除之前先查找数据是否存在。
name_list = ['1', '2', '3', '4', '5']
# 判断数据在指定列表里面,如果在返回true,不在返回false
result = '5' in name_list
print(result)
result = '爱' not in name_list
print(result)
result = '6' in name_list
print(result)
# 补充 除了列表可以结合in和notin 使用外,字符串和元祖也可以结合in和not in使用
结果
True
True
False
7.3 删除元素(del,pop,remove)
说明
name_list = ['a', 'bbbb', 'edvvs', 'fngjsf']
print(name_list)\
# 删除列表中的一部分数据
del name_list[0]
print(name_list)
# 删除列表中的数据并返回删除后的数据
name_list = ['a', 'bbbb', 'edvvs', 'fngjsf']
value = name_list.pop(2)
print('删除的数据为:', value)
print('删除后的列表为:', name_list)
# 删除的书架上必须在列表中
name_list = ['a', 'bbbb', 'edvvs', 'fngjsf']
name_list.remove('bbbb')
print('remove删除后的列表为:', name_list)
结果
['a', 'bbbb', 'edvvs', 'fngjsf']
['bbbb', 'edvvs', 'fngjsf']
删除的数据为: edvvs
删除后的列表为: ['a', 'bbbb', 'fngjsf']
remove删除后的列表为: ['a', 'edvvs', 'fngjsf']
7.2 根据下标修改数据
name_list = ['a', 'b', 'c', 'd']
name_list[-1] = 'm'
print(name_list)
name_list[0] = '1'
print(name_list)
name_list = ['1', '2', '3']
name_list[:2] = ['a','bbbb', 'edvvs', 'fngjsf']
print(name_list)
结果
['a', 'b', 'c', 'm']
['1', 'b', 'c', 'm']
['a', 'bbbb', 'edvvs', 'fngjsf', '3']
7.1 append,extend,insert
append 将另一个集合中的元素逐一添加到列表中
name_list = ['a', 'b', 'c', 'd']
# 添加列表元素
name_list.append('e')
print(name_list)
name_list.insert(0, 'f')
print(name_list)
# 扩展一组数据
my_list = ['1', '2', '3']
#name_list.append(my_list)
#print(name_list)
name_list.extend(my_list)
print(name_list)
结果
['a', 'b', 'c', 'd', 'e']
['f', 'a', 'b', 'c', 'd', 'e']
['f', 'a', 'b', 'c', 'd', 'e', '1', '2', '3']
6 列表遍历循环
5 列表
列表是容器类型,可以存储多个任意类型的数据。
表现形式:[a, b, c …, n]
列表类型:list
name_list = ['ABC', 'abc', 'bcd']
print(name_list[0])
print(name_list[1])
print(name_list[2])
# 不限制数据类型
name_list = ['ABC', 1, 3.14, [1, 2]]
print(name_list)
# 列表取值可以根据下标完成
value = name_list[1]
print(value)
value = name_list[-1]
print(value)
# 切片可以获取列表中的一部分数据
result = name_list[:2]
print(result, type(result))
结果
ABC
abc
bcd
['ABC', 1, 3.14, [1, 2]]
1
[1, 2]
['ABC', 1] <class 'list'>
4 字符串
4.5 字符串的常见操作
4.5.3 partition,rpartition,
4.5.2 replace,split,join
# 字符串常见操作,
# replace,对指定的字符串进行替换
# split,根据指定数据对字符串进行分割
# join,字符串拼接,返回一个拼接后的字符串(new)、
my_str = 'hello'
new_str = my_str.replace('l', 'w')
print(new_str, my_str)
new_str = my_str.replace('l','w',1)
print(new_str)
print('============')
# 分割处理split
my_str = '香蕉#苹果#葡萄'
result = my_str.split('#')
print(result, my_str)
# 指定分割次数
result = my_str.split('#', 1)
print(result, my_str)
print('==========')
# join操作
my_str = 'abc'
new_str = '_'.join(my_str)
print(new_str, my_str)
print('==========')
# 数组操作
my_list = ['A', 'B', 'C']
result = '#'.join(my_list)
print(result, my_list)
结果
hewwo hello
hewlo
============
['香蕉', '苹果', '葡萄'] 香蕉#苹果#葡萄
['香蕉', '苹果#葡萄'] 香蕉#苹果#葡萄
==========
a_b_c abc
==========
A#B#C ['A', 'B', 'C']
4.5.1 find,count,index
my_str = 'hello'
index = my_str.find('e')
print(index)
index = my_str.find('x')
print(index)
index = my_str.find('1', 0, 3)
print(index)
# index根据指定下标的时候,如果数据不存在则崩溃
result = my_str.index('e', 1, 4)
print(result)
print('===============')
my_str = 'hello'
result = my_str.count('l')
print(result)
result = my_str.count('x')
print(result)
result = my_str.count('l', 0, 3)
print(result)
4.4 切片
4.4.2 步长为负数
my_str = 'hello'
# 从倒数第一个数据获取到倒数第2个
# 步长为负数,表示从右往左取值
result = my_str[-1:-3:-1]
print(result)
# 结束下标不指定,默认获取到正数第一个数据
result = my_str[1::-1]
print(result)
# 从倒数第一个取到倒数最后一个
result = my_str[-1::-1]
print(result)
# 字符串反转的简写方式
result = my_str[::-1]
print(result)
结果
ol
eh
olleh
olleh
4.4.1 步长为正数
从左往右取值。
my_str = 'distribution'
result = my_str[0:2]
print(result)
result = my_str[:2]
print(result)
result = my_str[3:5]
print(result)
# 获取所有数据
result = my_str[0:12]
print(result)
result = my_str[:]
print(result)
# 默认步长是1,步长是正数,结束下标不指定能获取到最后一个数据
result = my_str[3:]
print(result)
# 2 步长
result = my_str[::2]
print(result)
结果
di
di
tr
distribution
distribution
tribution
dsrbto
4.3 下标
字符串实际上就是字符的数组,支持下标索引,从0开始。
下标有整数下标和负数下标,0表示第一个数据,-1表示最后一个数据
# 注意a前面的空格
name = ' abdce'
print(name[0])
print(name[1])
print(name[2])
print(name[-1])
index = 0
while index < len(name):
value = name[index]
print(value)
index += 1
# 获取字符串的长度
current_len = len(name)
print("name的长度为:", current_len)
结果
a
b
e
a
b
d
c
e
name的长度为: 6
4.2 f-strings(python3.6版本以上应用)
f-strings提供一种简单易读的方式,可以在字符串中包含python表达式,f-strings以字符’f’或者‘F’为前缀。
name = input("name:")
age = input("age:")
msg = f"姓名:{name}: 年龄:{age}"
print(msg, type(msg))
num1 = float(input("请输入num1:"))
num2 = float(input("请输入num2:"))
msg = F'{num1}+{num2} = {num1+num2}'
print(msg, type(msg))
结果
请输入num1:2
请输入num2:4
2.0+4.0 = 6.0 <class 'str'>
4.1 字符串介绍
多个字符的集合,带有单引号、双引号、3单引号、3双引号的数据。
my_str1 = 'a'
my_str2 = "ab"
my_str3 = '''abc '''
my_str4 = """abcd """
print(my_str1)
print(my_str2)
print(my_str3)
print(my_str4)
结果
a
ab
abc
abcd
3 循环语句
3.5 循环语句结合else语句使用
num = 1
while num <= 5:
print(num)
if num == 3:
break
num += 1
else:
print("Ok")
# 循环语句结合else语句使用的时候,只要循环语句里没有执行break,就会执行else。
my_str = "how are you"
search_data = input("请输入:")
# 遍历字符串,一次性判断查找是否有指定的数据
for value in my_str:
if value == search_data:
print("找到了,数据为:", value)
break
else:
print("数据不存在")
3.4 break continue
- 只能在循环语句里面使用,不能单独使用。
- break作用:让break所在的循环结束,循环结束。
- continue:结束当前一次循环,然后可以继续执行下次循环。循环并没有结束。
num = 1
while num <= 1:
print(num)
if num == 3:
break
num += 1
print("========")
for value in range(1, 6):
if value == 3:
continue
print(value)
3.3 for 循环
依次获取容器类的数据
name = 'itheima'
for x in name:
print(x, end=" ")
for 结合range使用
# range(data),data是结束数据,开始数据不指定,默认是0
for value in range(3):
print("当前范围的数字是:", value)
print("==============")
for x in range(1, 6, 2):
print(x)
print("==============")
for y in range(3, 0, -1):
print(y, end=" ")
结果
当前范围的数字是: 0
当前范围的数字是: 1
当前范围的数字是: 2
==============
1
3
5
==============
3 2 1
3.2 while嵌套格式
while 条件1:
满足条件1,do 1
while 条件2:
满足条件2,do a
count = 1
while count <= 4:
print("当前循环%d"% count)
inner_count = 1
while inner_count <= 3:
print("ok")
inner_count += 1
count += 1
结果
当前循环1
ok
ok
ok
当前循环2
ok
ok
ok
当前循环3
ok
ok
ok
当前循环4
ok
ok
ok
row = 1
while row <= 5:
col = 1
while col <= 5:
print("*", end=" ")
col += 1
# 当内层循环执行完成,说明当前这一行星星打印完毕,需要换一行打印
print("")
row += 1
结果
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
3.1 while
语法格式
while 判断条件:
条件成立,会执循环语句里面的代码
提示:while会重复判断条件是否成立,只要满足循环条件,代码就会执行
count = 1
while count <= 3:
print("OK")
count += 1
# 注意:条件始终成立时,会出现死循环。
i = 5
while i >= 0:
print("当前循环第%d次" % i)
i -= 1
i = 1
num = 0
while i <= 100:
i += 1
num += i
# num = num + i
print("当前循环第%d次" % i)
print("当前num值为:%d" % num)
print("结果为:%d"% num)
i = 1
num = 0
while i <= 100:
if i % 2 == 0:
num += i
print("当前循环第%d次" % i)
i += 1
# num = num + i
print("当前num值为:%d" % num)
print("结果为:%d"% num)