模块引用
模块在文件头部引用一次即可生效,打印python全局环境变量
1 | import sys |
打印当前脚本路径
1 | import sys |
列出文件夹中的文件信息,使用
os.popen(command)
可以直接调用系统命令
1 | import os |
创建文件夹
1 | import os |
三元运算
如果 b < c 条件成立 d = 变量a的值,如果条件不成立 d = 变量c的值
1 | a,b,c = 1,2,3 |
字符类型转换
将字符串编码成字节包(Byte类型)
1 | msg = "你好" |
字节包解码为将字符串
1 | msg3 = msg2.decode(encoding="utf-8") |
列表
打印列表
1 | names = ["ZhangXiaoFan","LinJingYu","ZengShuShu","ZhouYiXian"] |
打印指定位置的姓名(第1个从0开始)
1 | names = ["ZhangXiaoFan","LinJingYu","ZengShuShu","ZhouYiXian"] |
打印第二,第三个姓名(从0开始包含第1个,不包含第3个)
1 | names = ["ZhangXiaoFan","LinJingYu","ZengShuShu","ZhouYiXian"] |
打印最后一个姓名
1 | names = ["ZhangXiaoFan","LinJingYu","ZengShuShu","ZhouYiXian"] |
打印最后两个
1 | names = ["ZhangXiaoFan","LinJingYu","ZengShuShu","ZhouYiXian"] |
打印前三个
1 | names = ["ZhangXiaoFan","LinJingYu","ZengShuShu","ZhouYiXian"] |
按照步长打印
1 | names = ["ZhangXiaoFan","LinJingYu","ZengShuShu","ZhouYiXian","TianBuYi","CangSong","ZengShuChang"] |
追加元素
追加到列表尾部
1 | names = ["ZhangXiaoFan","LinJingYu","ZengShuShu","ZhouYiXian"] |
追加到指定位置
1 | names = ["ZhangXiaoFan","LinJingYu","ZengShuShu","ZhouYiXian"] |
修改元素
1 | names = ["ZhangXiaoFan","LinJingYu","ZengShuShu","ZhouYiXian"] |
删除元素
删除指定元素名
1 | names = ["ZhangXiaoFan","LinJingYu","ZengShuShu","ZhouYiXian"] |
删除指定下标位置的元素(如果不指定参数默认删除最后一个)
1 | names = ["ZhangXiaoFan","LinJingYu","ZengShuShu","ZhouYiXian"] |
删除指定下标位置的元素
1 | names = ["ZhangXiaoFan","LinJingYu","ZengShuShu","ZhouYiXian"] |
查找元素
通过元素名获取下标
1 | names = ["ZhangXiaoFan","LinJingYu","ZengShuShu","ZhouYiXian"] |
通过下标获取元素名
1 | names = ["ZhangXiaoFan","LinJingYu","ZengShuShu","ZhouYiXian"] |
查找元素出现次数
1 | names = ["ZhangXiaoFan","LinJingYu","ZengShuShu","ZhouYiXian","ZhangXiaoFan"] |
清空列表
1 | names = ["ZhangXiaoFan","LinJingYu","ZengShuShu","ZhouYiXian","ZhangXiaoFan"] |
反转列表元素
1 | names = ["ZhangXiaoFan","LinJingYu","ZengShuShu","ZhouYiXian"] |
元素排序
默认排序方式(特殊字符>数字>大写字母>小写字母)
1 | names = ["ZhangXiaoFan","LinJingYu","zengShuShu","#ZhouYiXian","1ZhangXiaoFan"] |
列表合并
1 | names = ["ZhangXiaoFan","LinJingYu","ZengShuShu"] |
列表复制
列表复制(与普通变量复制不同列表中的复制等于两个列表指向同一个内存空间,其中一个值更改另一个会同步)
1 | names = ["ZhangXiaoFan","LinJingYu","ZengShuShu"] |
浅copy直接复制一份变量到新的内存空间,源变量值更改不影响copy后的
1 | names = ["ZhangXiaoFan","LinJingYu","ZengShuShu"] |
深copy引用其内存空间地址,源变量值更改会影响copyhou的
1 | names = ["ZhangXiaoFan","LinJingYu",["TianBuYi","CangSong","ZengShuChang"],"ZengShuShu"] |
copy一份完全独立的列表
1 | import copy |
元组
只读列表(只允许查,切片)
1 | names = ("ZengShuShu","ZhangXiaoFan","LinJingYu","TianBuYi","CangSong","ZengShuChang","ZengShuShu") |
购物车程序:
需求:
1.启动程序后,让用户输入工资,然后打印商品列表
2.允许用户根据商品编号购买商品
3.用户选择商品后,检测余额是否够,够就添加购物车扣款,否则提醒
4.可随时退出,退出时打印已经购买的商品和余额
实现方法:
1.创建两个列表商品列表,购物车列表
2.用户输入工资
2.1.判断用户输入的工资是否是数字,如果是数字则转换为int类型否则退出并给出提示
3.循环打印商品列表
4.让用户输入购买的商品编号
3.1.判断用户输入的是否是数字,并且商品编号中存在
3.2.判断用户余额是否大于等于选择商品的价格,如果是则添加商品信息到购物车,扣除商品价格并给出提示
3.3.判断如果用户输入的是q,则打印购物车列表,提示信息,余额;否则打印输入编号异常
code
1 | # Author: Yi Xuan |
字符串处理
1 | name = 'my name is\t Yi Xuan' |
字典
1 | # Author: Yi Xuan |