基础的函数学习
本节内容
- 列表、元组操作
- 字符串操作
- 字典操作
- 集合操作
- 文件操作
- 字符编码与转码
1. 列表、元组操作
列表是我们最以后最常用的数据类型之一,通过列表可以对数据实现最方便的存储、修改等操作
定义列表
1
|
names = [ 'Alex' , "Tenglan" , 'Eric' ] |
通过下标访问列表中的元素,下标从0开始计数
1
2
3
4
5
6
7
8
|
>>> names[ 0 ] 'Alex' >>> names[ 2 ] 'Eric' >>> names[ - 1 ] 'Eric' >>> names[ - 2 ] #还可以倒着取 'Tenglan' |
切片:取多个元素

追加

插入

修改

删除

扩展

拷贝

copy真的这么简单么?那我还讲个屁。。。
统计

排序&翻转

获取下标

元组
元组其实跟列表差不多,也是存一组数,只不是它一旦创建,便不能再修改,所以又叫只读列表
语法
1
|
names = ( "alex" , "jack" , "eric" ) |
它只有2个方法,一个是count,一个是index,完毕。
集合
主要作用就是去重,把一个list编程集合就自动去重了
关系测试,交集并集差集等
set
or ,& 交集,interc 取共有的元素
and ,|, 并集 ,union 全部的元素
difference “ - ”差集,我有你没有,
symmetric_difference “^””对称差集,取你有我没有,我有你没有的
判断 issuperset 父集 >
issubset 子集 <
内置函数:
map
fil
reduce
文件的基本操作:
f = open("name","r",enconding="",newline="") # r 只读, w 只写 ,a 追加 r+读写,w+写读,a+写读
with open
data = f.read()
f.readable() #判断是否只读模式
f.readline() ,end="" 去尾 #读一行
f.readlines() # 读完
---- 写入编码encode,读取解码decode
f.write ("....\n")
f.writelines([ ])
f.tell #光标位置 --字节
f.seek(0) #设置光标位置 --字节
迭代器&生成器
(i for i in range(10))
def test():
yield 10
装饰器
本质就是函数,为其他函数添加功能
原则:
1,不修改被修改函数的源代码
2,不修改被修饰函数的调用方式
装饰器 = 高阶函数+函数嵌套+闭包

#简单示例 def timmer(func): def wrapper(): start_time = time.time() func() stop_time = time.time() print("程序执行的时间:%s"%(stop_time-start_time)) return wrapper @timmer # test = timmer(test) def test(): time.sleep(2) print("执行test函数完毕") # test = timmer(test) test()
current_usr = {"username":None,"login":False} def auth(auth_type="fileDb"): def user_auth(func): def wrapper(*args,**kwargs): print("--->用户认证类型是%s"%auth_type) if auth_type == "fileDb": if current_usr["username"] and current_usr["login"]: res = func(*args, **kwargs) return res u_name =input("请输入账户名:>>>").strip() u_pwd = input("输入密码:>>>").strip() for u_dic in ret: if u_name == u_dic["name"] and u_pwd == u_dic["passwd"]: current_usr["username"] = u_name current_usr["login"]=True res = func(*args, **kwargs) return res else: print("登入失败,请重新输入") elif auth_type=="ladp": print("--->用户认证类型是%s"%auth_type) else: print("whoTM的知道") return wrapper return user_auth