工程师们大家好,配套免费视频(平时上班周末录制)
文章目录
1.集合运算
运算符 | 描述 | 支持的容器类型 |
---|---|---|
+ | 合并 | 字符串、列表、元组 |
* | 复制 | 字符串、列表、元组 |
in | 元素是否存在 | 字符串、列表、元组、字典 |
not in | 元素是否不存在 | 字符串、列表、元组、字典 |
1.1+号
# 1.字符串
str1 = 'ab'
str2 = 'cd'
str3 = str1 + str2
print(str3) # abcd
a = 1
# str_a = str1 + a # 报错,can only concatenate str (not "int") to str
a_ = str1 + str(a) # 需要都转了字符串
print(a_)
# 2.列表
list1 = [1, 2]
list2 = [3, 4]
list3 = list1 + list2
print(list3)
# 3.元组
t1 = (1, 2)
t2 = (3, 4)
t3 = t1 + t2
print(t3)
# 4.集合
set1 = {1, 2}
set2 = {3, 4}
# 不支持
# set3 = set1 + set2 # TypeError: unsupported operand type(s) for +: 'set' and 'set'
# 5.字典
dict1 = {'name': 'zhangsan'}
dict2 = {'age': 10}
# 不支持
dict3 = dict1 + dict2 # TypeError: unsupported operand type(s) for +: 'dict' and 'dict'
1.2*号
# 1.字符串
str1 = 'a'
str_10 = str1 * 10
print(str_10) # aaaaaaaaaa
# 2.列表
list1 = ['天']
list_10 = list1 * 10 # ['天', '天', '天', '天', '天', '天', '天', '天', '天', '天']
print(list_10)
# 3.元组
tuple1 = (1,) # 注意定义一个元组也要加逗号
tuple1_10 = tuple1 * 10
print(tuple1_10) # (1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
1.3in/not in
# 1. 字符串
print('a' in 'abcd') # True
print('a' not in 'abcd') # False
# 2. 列表
list1 = ['a', 'b', 'c', 'd']
print('a' in list1) # True
print('a' not in list1) # False
# 3. 元组
t1 = ('a', 'b', 'c', 'd')
print('aa' in t1) # False
print('aa' not in t1) # True
# 4.集合
set1 = {'a', 'b', 'c', 'd'}
print('a' in set1) # True
print('a' not in set1) # False
# 5.字典
dict1 = {'name': '张三', 'age': 10}
print('name' in dict1) # True
print('name' not in dict1) # False
2. 公共方法
函数 | 描述 |
---|---|
len() | 计算容器中元素个数 |
del 或 del() | 删除 |
max() | 返回容器中元素最大值 |
min() | 返回容器中元素最小值 |
range(start, end, step) | 生成从start到end的数字,步长为 step,供for循环使用 |
enumerate() | 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。 |
前面四个,要么简单,要么前面已经展示过了
2.1range
# 1. 字符串
print('-----字符串遍历-----')
str1 = 'abcde'
for i in range(len(str1)):
print(str1[i], end='\t')
print()
# 2. 列表
print('-----列表遍历-----')
list1 = ['a', 'b', 'c', 'd']
for i in range(len(list1)):
print(list1[i], end='\t')
print()
# 3. 元组
print('-----元组遍历-----')
t1 = ('a', 'b', 'c', 'd')
for i in range(len(t1)):
print(t1[i], end='\t')
print()
# 4.集合
print('-----集合遍历 报错 因为集合是无序的 那么下标就没有意义-----')
set1 = {'a', 'b', 'c', 'd'}
for i in range(len(set1)):
print(t1[set1], end='\t')
2.2enumerate()
# enumerate内置函数 主要用于字符串 元组 列表等输出下标
str1 = 'abcde'
# enumerate方法返回一个元组列表(1,'a'),(2,'b')....等
# 前面1234是下标 由start指定 默认是0
for index, value in enumerate(str1, start=1):
print(index, '---', value)
'''
结果:
1 --- a
2 --- b
3 --- c
4 --- d
5 --- e
'''
# 其他列表,元组类似了 可以自己去写测试
# 字典操作 这里的value代表的是key,然后可以通过前面学习key的遍历
student = {'name': '张三', 'age': 10}
for index, value in enumerate(student):
print(index, value) # 打印0 name 1age
3.转换
强制类型转换
str( ):可以把其他类型数据转化为字符串类型
int( ):可以把其他类型数据转化为整型
float( ):可以把其他类型数据转化为浮点型
bool( ):可以把其他类型数据转化为布尔类型
list( ):可以把其他类型数据转化为列表类型
tuple( ):可以把其他类型数据转化为元组类型
dict( ):可以把其他类型数据转化为字典类型
set( ):可以把其他类型数据转化为集合类型
3.1其他转字符串
所有类型都可以转化为字符串类型。
print('-----int类型转换为字符串,其他类似-----')
a = 1 # int类型
str_a = str(a) # int类型强转为字符串
print(str_a, type(str_a)) # 1 <class 'str'>
print('-----list列表类型转换为字符串-----')
list1 = ['a', 'b', 'c', 'd']
str_list1 = str(list1)
print(str_list1, type(str_list1)) # ['a', 'b', 'c', 'd'] <class 'str'>
join_list1 = '-'.join(list1)
print(join_list1, type(join_list1))
list2 = [1, 2, 3, 4]
# 如果list中包含数字会报错TypeError: sequence item 0: expected str instance, int found
# join_list2 = '-'.join(list2)
# 先循环list2里面的元素 然后通过s%转为字符串 把id的值给%s
join_list2 = '-'.join('%s' % id for id in list2)
# 或者 直接把id强转为str类型
join_list2 = '-'.join(str(id) for id in list2)
print(join_list2) # 1-2-3-4
print('-----元组tuple类型转换为字符串-----')
tuple1 = (1, 2, 3, 4)
str_tuple1 = str(tuple1)
print(str_tuple1, type(str_tuple1)) # (1, 2, 3, 4) <class 'str'>
str_tuple1 = '-'.join(str(aa) for aa in tuple1)
print(str_tuple1, type(str_tuple1)) # 1-2-3-4 <class 'str'>
print('-----集合set类型转换为字符串-----')
set1 = {1, 2, 3, 4}
str_set1 = str(set1)
print(str_set1, type(str_set1)) # {1, 2, 3, 4} <class 'str'>
str_set1 = '-'.join(str(aa) for aa in set1)
print(str_set1, type(str_set1)) # 1-2-3-4 <class 'str'>
print('-----字典dict类型转换为字符串-----')
a = {"aa": "a", "bb": "b"} # dict
res = str(a)
print(res, type(res)) # {'aa': 'a', 'bb': 'b'} <class 'str'>
3.2其他类型转列表
print('---------字符串转列表----------')
str1 = 'abc123'
list_str1 = list(str1)
print(list_str1, type(list_str1)) # ['a', 'b', 'c', '1', '2', '3'] <class 'list'>
print('---------元组转列表----------')
tuple1 = (1, 2, 3, 4)
list_tuple1 = list(tuple1)
print(list_tuple1, type(list_tuple1)) # [1, 2, 3, 4] <class 'list'>
print('---------字典转列表----------')
dict1 = {'name': '张三', 'age': 10, 'address': '成都'}
# key转为列表
list_dict1_key = list(dict1)
print(list_dict1_key, type(list_dict1_key)) # ['name', 'age', 'address'] <class 'list'>
# value转为列表 先获得字典的item 然后把value挨着取出形成列表
list_dict1_value = [value for key, value in dict1.items()]
print(list_dict1_value, type(list_dict1_value)) # ['张三', 10, '成都'] <class 'list'>
3.3其他类型转元组
同上,只不过使用tuple()
3.4其他类型转集合
同上,只不过使用set
print('---------字符串转集合,会去重----------')
str1 = 'aabc123'
set_str1 = set(str1)
print(set_str1, type(set_str1)) # {'3', 'c', '1', '2', 'a', 'b'} <class 'set'>
3.5其他类型转dict
print('---------列表转dict----------')
list1 = ['name', 'name', 'age', 'address']
list2 = ['张三', '李四', 10, '成都']
dict1 = {list1[i]: list2[i] for i in range(len(list1))}
# name去重了 李四覆盖了张三
print(dict1) # {'name': '李四', 'age': 10, 'address': '成都'}
# 还可以写条件 比如下标小于2
dict1 = {list1[i]: list2[i] for i in range(len(list1)) if i < 2}
print(dict1) # {'name': '李四'} 只有 0根1 1name把0的覆盖了
iterator = zip(list1, list2)
print(iterator) # zip类型
# 将zip类型强转为字典类型
print(dict(iterator)) # {'name': '李四', 'age': 10, 'address': '成都'}
4.循环集合简单综合练习
水果超市(毕竟是控制台练习,降低部分难度,与真实略有差距)
1.进入界面,用户可选择注册,或者登录
注册要求:
用户名为11位
密码必须大于11位,但是至少包含数字、大小写字母、其他字符中三种
2.注册成功后,进入登录界面,用户可登录
3.登录成功欢迎用户来到水果超市界面,选择水果
序号 水果 价格/斤
1 苹果 5
2 榴莲 25
3 香蕉 3
4 橘子 8
4.循环提示用户选择水果,选择完成后打印用户购买详细信息
退出系统
可以自由实现,能实现功能即可。下面是参考代码实现:
import sys # 这个没学习 先用一下
print('---------欢迎来到水果超市----------')
login_dict = {} # 用来保存 注册的用户列表 key-value形式 key为用户名
while True:
print('1.用户注册')
print('2.用户登录')
print('0.退出程序') # 简单用一下 表示可以退出 后面就不退出了
choice = int(input('请选择:'))
if choice == 0:
sys.exit(0) # 结束程序
if choice == 1:
while True:
username = input('请输入用户名:')
if not username or len(username) != 11:
print('用户名不能为空且长度为11位')
continue
# 因为是简单的版本,不需要校验用户名是否存在
# 用户名输入成功后,输入密码(密码循环输入)
while True:
print('密码必须大于11位,但是至少包含数字、大小写字母、其他字符中三种')
password = input('请输入密码')
if password and len(password) > 11:
i = j = k = m = 0 # 定义ijkm 都等于0
for ch in password:
if ch.isdigit(): # 判断是否为数字
i += 1
elif 90 >= ord(ch) >= 65: # 根据ascii码表判断是否为大写字母:百度百科可看ascii码表
j += 1
elif 97 <= ord(ch) <= 122: # 根据ascii码表判断是否为小写字母
k += 1
else:
m += 1
# 循环 i,j,k,m四个元素 然后留下大于0的 如果个数>=3个说明满足
if len([value for value in [i, j, k, m] if value > 0]) >= 3:
print('恭喜注册成功')
login_dict[username] = password
break
break # 跳出用户名密码循环
choice = 2 # 把choice改成2
if choice == 2:
if len(login_dict) == 0:
print('请先注册')
continue
while True:
print('-----请输入正确的用户名密码登录-----')
username = input('请输入用户名')
password = input('请输入密码')
if login_dict.get(username) != password:
continue # 登录失败继续输入
print('登录成功...欢迎选购')
break
break # 跳出操作循环
# 用一个嵌套字典来装水果
fruit_dict = {1: ('苹果', 5), 2: ('榴莲', 25), 3: ('香蕉', 3), 4: ('橘子', 8)}
user_buys = {} # 存储用户购买的信息 key:水果序号 value是数量(多少斤)
# 打印一下水果列表
for key, value in fruit_dict.items():
print(key, '\t', value[0], '\t', value[1])
while True:
num = int(input('请输入序号'))
quantity = int(input('请输入数量'))
if num > 0 and quantity > 0:
user_buys[num] = quantity
else:
print('请输入正确的序号跟数量')
print('继续购买,请输入1,退出请按0')
choice = int(input('请选择是否继续购买'))
if choice == 0:
break # 跳出循环
print(f'{list(login_dict)[0]},您好,您的购买清单为:')
print('序号', '\t', '名称', '\t', '单价', '\t', '数量', '\t', '总价格')
count = 0
for key, value in user_buys.items():
print(key, '\t', fruit_dict[key][0], '\t', fruit_dict[key][1], '\t', value, '\t', fruit_dict[key][1] * value)
count += fruit_dict[key][1] * value
print('总价格%d' % count)
print('谢谢使用,再见')