目录
一、函数
enumerate 函数
1. 作用
2. 用法
zip 函数
1. 作用
2. 使用
3. zip(*AB)
lambda 函数
1. 作用
2. 使用
operator 模块(代替 cmp 函数)
1. 导入 operator 模块
2. 使用
3. 功能
strtobool 函数
1. 作用
2. 使用
set 函数
1. set( ) 不能针对 双列表。
2. set( ) 的结果是集合。
3. set( ) 的结果是乱序,若想不打乱顺序,结合sort( ),即可保留原顺序。
4. 结合 &、|、-,可以求交集、并集、差集。
hasattr() 函数
Round函数 & "%.2f"%( )
1. 注意
2. 用法
3. 举例
4. 理解
二、方法
setdefault() 方法
1. 针对字典
2. “不存在的key”会被赋新值,“已存在的key”不会被赋新值(已存在的值不改变)。
3. 写法
update() 方法
1. 更新字典
2. 作用
3. 写法
extend() 方法
1. 作用
2. 与 append() 的不同
insert() 方法
1. 针对列表
2. 写法
3. 与 append() 的不同
sort() 方法 & sorted 函数
1. sorted(obj) 函数
2. list.sort( ) 方法
__init__() 方法
1. 作用
2. 对requests不起作用
intersection() 方法
1. 针对:求交集
2. 特征
3. 使用
(1)两者交集
(2)多者交集
(3)参数的类型可以不同
os.getcwd() 方法
1. 作用
2. 举例
sys.path.append() 方法
1. 意义
2. 举例
datetime.strptime() 方法
1. 用法
2. 注意
3. 举例
datetime.timedelta() 方法
1. 用法
2. 举例
join() 方法
1. 作用
2. 注意
3. 例如
python的函数是独立的调用。如 len(list)、max()、list(seq)等。
python的方法是需要变量+点来调用。如 list.append(obj)、list.insert(index, obj)等。
一、函数
enumerate 函数
1. 作用
提供当前元素的索引
2. 用法
book_data = [['数据结构', 'IT', '萝卜干'], ['数据库原理', 'IT', '萝卜丝']] book_title = ['bookname', 'booktype', 'author'] data_list = list() for book in book_data: idx = 0 book_dict = dict() for i in book: book_dict[book_title[idx]] = i idx += 1 data_list.append(book_dict) # idx 是 enumerate 函数生成的索引值 data_list = [{book_title[idx]: i for idx, i in enumerate(book)} for book in book_data] # data_list 的值为:[{'bookname': '数据结构', 'booktype': 'IT', 'author': '萝卜干'}, {'bookname': '数据库原理', 'booktype': 'IT', 'author': '萝卜丝'}]
讯享网
zip 函数
1. 作用
是python的内置函数。
将多组列表,打包为一个包含元组的列表。结果是一个对象形式。
2. 使用
(1)zip() 之后的结果只能“使用一次”;
(2)zip() 以最短的为准(如下方例子结果是2个元组,而不是3个)。
讯享网a = [1, 2, 3] b = [4, 5] c = [1, 2] abc = zip(a, b,c) print(abc) # <zip object at 0x0000000000BB4C00>。 print(list(abc)) # [(1, 4, 1), (2, 5, 2)]
(3)zip的结果整体,是一个对象形式,若想转换为其他形式,比如数组,就用list函数。
(4)zip的结果里的元素,都是元组形式,若想转换为其他形式,比如数组,就用map(list, XX)函数, 把zip(*a)后的每一个元素转化为list。但需注意,map之后的结果也是对象形式。需再次用list把整体转成列表形式。
a = [1, 2, 3] b = [4, 5] c = [1, 2] abc_zip = zip(a, b, c) abc_list = list(zip(a, b, c)) abc_map = map(list, zip(a, b, c)) abc_map_list = list(map(list, zip(a, b, c))) print('abc_zip', abc_zip, '\n', 'abc_list', abc_list, '\n', 'abc_map', abc_map, '\n', 'abc_map_list', abc_map_list) # 其中, zip(a, b, c) 的结果是对象:<zip object at 0x0000000000BB4C00>。 # list(zip(a, b, c)) 的结果:[(1, 4, 1), (2, 5, 2)]。 # map(list, zip(a, b, c)) 的结果是对象:<map object at 0x0000000000F830A0>。 # list(map(list, zip(a, b, c))) 的结果:[[1, 4, 1], [2, 5, 2]]
3. zip(*AB)
zip(*AB) 是将AB复原成zip之前的数据。 (与 zip(AB) 相反)
讯享网zipped = [(1, 4), (2, 5), (3, 6)] zipped_revert = zip(*zipped) print('zipped_rev', list(zipped_revert)) # [(1, 2, 3), (4, 5, 6)]
lambda 函数
1. 作用
写法:
func = lambda 参数1, 参数2, 参数3 ...: 运算式
def func(参数1, 参数2, 参数3 ...): 运算式 return 回传值
2. 使用
# 基本使用 func = lambda x,y: x*y res = func(2,3) print('res=', res) # res= 6
# 简写 res = (lambda x,y: x*y)(2,3) print('简写 res=', res) # 简写 res= 6
一般是和其他函数搭配使用的。比如map、filter、reduce函数。
# (1)查询得值 filter nums = [1,23,34,45,8,9,10,12] res = filter(lambda x: x>10, nums) # 其中,lambda x: x>10是一个整体,nums是一个整体,分别对应filter的第一个参数和第二个参数。 print('res=', list(res)) # res= [23, 34, 45, 12] # (2-1)组装得值 map nums = [1,-1,3,5,6,2,8,63,0] res = map(lambda x: x+100, nums) print('res=', list(res)) # res= [101, 99, 103, 105, 106, 102, 108, 163, 100] # (2-2)组装得值 map a1=[9,8,7] a2=[6,5,4] dict_a = dict(map(lambda x, y: [x,y], a1,a2)) list_b = list(map(lambda x, y: x+y, a1,a2)) # 其中,lambda x, y: [x,y]是一个整体,对应map的第一个位置的参数; # a1和a2对应map的第二个位置的参数。 print('dict_a=', dict_a) print('list_b=', list_b) # dict_a= {9: 6, 8: 5, 7: 4} # list_b= [15, 13, 11] # (3)迭代元素执行运算 reduce from functools import reduce def add(a, b): return a+b res1 = reduce(add, [1,2,3,4,5]) # 计算列表和:1+2+3+4+5 res2 = reduce(lambda x, y: x+y, [1,2,3,4,5]) # 使用 lambda 匿名函数 print('迭代使用方法 res1=', res1) print('使用lambda函数 res2=', res2) # 迭代使用方法 res1= 15 # 使用lambda函数 res2= 15
其他:将列表中的数值int元素转换为str字串
num_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] new_obj = map(lambda x:str(x), num_list) # <map object at 0x0000000006FEF8B0> new_list = list(new_obj) # ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] # 另一种更简单的写法 num_list = [0,1,2,3,4,5,6,7,8,9] new_list = [str(x) for x in num_list] # ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
operator 模块(代替 cmp 函数)
cmp函数是比较两个值的关系,可是python3中已经被弃用。
所以,改用operator模块。则,重点讲解operator模块。
1. 导入 operator 模块
import operator
2. 使用
以 equal 比较是否相等为例。
list1, list2 = [456, 'abc'], [456, 'abc'] list3 = list2 + [786] res = operator.eq(list1, list2) res2 = operator.eq(list1, list3) print('res=', res, '\n', 'res2=', res2) # res= True # res2= False
3. 功能
| 函数 | 含义 |
|---|---|
| operator.eq(a, b) | a == b |
| operator.ne(a, b) |
a != b |
| operator.lt(a,b) | a < b |
| operator.le(a, b) | a <= b |
| operator.gt(a, b) | a > b |
| operator.ge(a, b) | a >= b |
strtobool 函数
1. 作用
检验子串,转换成boolean值,返回整数值结果 1 or 0 。1 代表True,0 代表False。
2. 使用
该函数只检验部分值,其余值均抛出 ValueError 异常。
| 能检验出 True 的值: |
'y', 'yes', 't', 'true', 'on', '1' |
| 能检验出 False 的值: | 'n', 'no', 'f', 'false', 'off', '0' |
from distutils.util import strtobool a,b,c,d,e,f = strtobool('y'), strtobool('yes'), strtobool('t'), strtobool('true'), strtobool('on'), strtobool('1') print(a,b,c,d,e,f) # 1 1 1 1 1 1
返回结果是整数值,若想转换成Boolean值,可以用 bool 函数。
from distutils.util import strtobool res = bool(strtobool('TRue')) print('res=', res) # res= True
set 函数
1. set( ) 不能针对 双列表。
2. set( ) 的结果是集合。
处理后的结果用 { } 包裹,类似于字典类型格式,但不同于字典。
3. set( ) 的结果是乱序,若想不打乱顺序,结合sort( ),即可保留原顺序。
4. 结合 &、|、-,可以求交集、并集、差集。
# 第一种:单纯去重 lis = [1,2,3,'a',4,5,3,2,4] newlist = list(set(lis)) print('newlist=', newlist) # 第二种:保留原顺序的去重 lis = [1,2,3,'a',4,5,3,2,4] newlist2 = list(set(lis)) newlist2.sort(key=lis.index) print('newlist2=', newlist2) # newlist= [1, 2, 3, 4, 5, 'a'] # newlist2= [1, 2, 3, 'a', 4, 5]
hasattr() 函数
作用:判断对象是否包含对应的属性。
例如:判断Book对象是否包含hastype,hasprice,hascover属性
class Book: booktype = '教育' bookprice = '¥60' testval = Book() # 判断Book对象是否包含hastype,hasprice,hascover属性 hastype = hasattr(testval, 'booktype') hasprice = hasattr(testval, 'bookprice') hascover = hasattr(testval, 'bookcover') print('hastype=', hastype, ',hasprice=', hasprice, ',hascover=', hascover ) # hastype= True ,hasprice= True ,hascover= False
Round函数 & "%.2f"%( )
1. 注意
round() 函数计算的结果不准确,最好使用 "%.2f"%( ) 代替。
2. 用法
将 round() 改用 "%.2f"%( )
3. 举例
res_rate = round(25/36, 2) * 100 # 改成 res_rate = "%.2f"%( (25/36)*100 )
4. 理解
格式是 "%.2f%%",其中,%.2f表示输出浮点数并保留两位小数。%%表示直接输出一个%。
格式是 "%.2f" % 33 ,结果是33.00。
格式是 "%.2f%%" % 33 ,结果是33.00%。
二、方法
setdefault() 方法
1. 针对字典
2. “不存在的key”会被赋新值,“已存在的key”不会被赋新值(已存在的值不改变)。
3. 写法
book_dict = {'bookname': '操作系统'} book_dict.setdefault('bookname', '数据结构') book_dict.setdefault('bookprice', '¥80') print('book_dict', book_dict) # book_dict 结果是 {'bookname': '操作系统', 'bookprice': '¥80'} # bookname 不会改变
update() 方法
1. 更新字典
2. 作用
用 update 将新字典更新到旧字典中时,旧字典的结果会有两种情况:
(1)有相同的键时:更新为新字典 key 对应的 value 值。
(2)有新的键时:将新字典 key、value 新增进旧字典中。
即,“不存在的key”会被赋新值,“已存在的key”也会被赋新值(已存在的值改变)。
3. 写法
book_dict = {'bookname': '操作系统', 'booktime': '2023'} book_dict.update({'bookname': '数据结构', 'bookprice': '¥80'}) print('book_dict', book_dict) # book_dict 结果是 {'bookname': '数据结构', 'booktime': '2023', 'bookprice': '¥80'} # bookname 更新了,并新增了 bookprice
extend() 方法
1. 作用
将另一个列表的所有元素添加到当前列表中。
2. 与 append() 的不同
append() 是将其他列表的整体,整块添加到当前列表中。
extend() 是遍历其他列表中的所有元素,每个元素添加到当前列表中。
mylist1 = ['a','b','c'] mylist2 = ['a','b','c'] list3 = [1,2,3] mylist1.append(list3) mylist2.extend(list3) print('mylist1', mylist1, '\n', 'mylist2', mylist2) # mylist1 ['a', 'b', 'c', [1, 2, 3]] # mylist2 ['a', 'b', 'c', 1, 2, 3]
insert() 方法
1. 针对列表
2. 写法
List.insert(位置index,对象元素)
3. 与 append() 的不同
insert() 常用于添加到指定位置,例如第一个位置。
sort() 方法 & sorted 函数
1. sorted(obj) 函数
(1)不会改变原数组。
(2)有返回值。
(3)针对对象。除了列表,针对元组和子串形式,也适用。
(4)对象里的不同类型数据,不能比较(可以先强制转换成同一类型)。
(5)区分大小写 A<B<a。
(6)降序排列,补充reverse属性。
(7)下方例子很重要。(包括key属性的使用、比较不同数据类型等)
mylist = ['A', 'a', 'A', 'B'] mylist2 = ['Abc', '1', 'ab'] mylist3 = [(1, 2), (3, 4), (5, 3), (6, 6), (3, 0), (10, 1)] mylist4 = ['1', 0, '3', '2'] # 默认升序排列 aa = sorted(mylist) print(aa) # ['A', 'A', 'B', 'a'] # 降序排列 bb = sorted(mylist, reverse=True) print(bb) # ['a', 'B', 'A', 'A'] # 全部转换为小写,再升序排列 cc = sorted(mylist, key=str.lower) print(cc) # ['A', 'a', 'A', 'B'] # 按照元素的长度,升序排列 dd = sorted(mylist2, key=len) print(dd) # ['1', 'ab', 'Abc'] # 利用key属性+指定方法,进行排序 def addEle(ele): return ele[0]+ele[1] ee = sorted(mylist3, key=addEle) # 执行完addEle方法后,会按照[3,7,8,12,3,11]进行升序排列 print(ee) # [(1, 2), (3, 0), (3, 4), (5, 3), (10, 1), (6, 6)] # 针对不同数据类型 ff = sorted(mylist4) print(ff) # '<' not supported between instances of 'int' and 'str' ff2 = sorted(mylist4, key = int) print(ff2) # res2= [0, '1', '2', '3']
2. list.sort( ) 方法
(1)会改变原数组。
(2)没有返回值(不能将其赋值给另一个变量,会得到一个None)。
(3)只能针对列表形式。
(4)不能搭配list方法(可以先用列表生成式,再用sort)。
# 下方两种方式的打印结果不同,前者return True,后者return False。 # 因为前者是直接比较两个排序结果,sort无返回值,所以最后是两个None相比。 # 但是后者是先排序,比较的是排序后的res1和res2本身。 s1, s2 = "abc", "bad" res1 = [i for i in s1] res2 = [i for i in s2] # 第一种 print('将排序后返回的结果,进行对比', res1.sort() == res2.sort()) # True # 第二种 res1.sort() res2.sort() print('先排序,再对比两者本身', res1 == res2) # False
参考文章:Python排序傻傻分不清?一文看透sorted与sort用法-腾讯云开发者社区-腾讯云
__init__() 方法
1. 作用
实例化类时,初始化值。
2. 对requests不起作用
请求接收的requests不会走__init__( )。
因为requests是链接前后端的API, 是直接通过get或post请求。
intersection() 方法
1. 针对:求交集
2. 特征
参数可以是列表、子串、集合、元组,结果一定是集合。
3. 使用
(1)两者交集
x = {"AAA", "BBB", "CCC"} y = {"AAA", "DDD", "EEE"} z = x.intersection(y) # {'AAA'}
(2)多者交集
x = {"a", "b", "c"} y = {"a", "d", "e"} z = {"a", "f", "g"} result = x.intersection(y, z) # {'a'}
(3)参数的类型可以不同
x = {"a", "b", "c"} y = ["a", "d"] z = 'a' result_y = x.intersection(y) # {'a'} result_z = x.intersection(z) # {'a'}
os.getcwd() 方法
1. 作用
返回当前工作目录。
os.getcwd() # 获取当前路径(当前目录并不是指脚本所在的目录,而是所运行脚本的目录,即运行终端显示的路径。)
2. 举例
import os currentFolder = os.getcwd() # 获取当前路径
sys.path.append() 方法
1. 意义
当需要引入的模块不在脚本运行路径下,可在该脚本开头加sys.path.append('xxx')。
相当于临时配置环境变量(替代“环境变量路径的配置”)。
2. 举例
引入指定路径下的文件(当前路径/当前目录名/文件名.后缀)
注意运行时,终端也要注意路径一致。
import os import sys currentFolder = os.getcwd() # 获取当前路径 sys.path.append(currentFolder) myfilename = currentFolder + "/当前目录名/文件名.后缀"
datetime.strptime() 方法
1. 用法
from datetime import datetime datetime.strptime(时间字串, '%Y%m%d')
2. 注意
方法里第1个参数,和第2个参数的格式得一致。
from datetime import datetime my_str = '' my_str2 = ' 10:55:31' date = datetime.strptime(my_str, '%Y%m%d') date = datetime.strptime(my_str2, '%Y-%m-%d %H:%M:%S')
3. 举例
若遇到日期比较问题:
TypeError("'>' not supported between instances of 'str' and 'datetime.datetime'",)
解决:
将 str 的变量用 datetime.strptime() 转换。
datetime.timedelta() 方法
1. 用法
给日期加减天数:timedelta(days=6)
2. 举例
datecode = '' deadline = datetime.strptime(bookdate, '%Y%m%d') + timedelta(days=6) if bookdate else None
join() 方法
1. 作用
将序列中元素,用指定字符,串接成新字符串。
2. 注意
元素必须为字符串。
3. 例如
my_list = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] my_str = "--".join(my_list) # '0--1--2--3--4--5--6--7--8--9'

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/120238.html