文章目录
本文主要记录一些个人学习python过程中的一些有用的、没用的、以及奇奇怪怪的知识。
本文持续更新…
1. partial
partial:固定一个函数的部分参数,接受一个函数和这个函数的部分参数作为输入,返回一个新的函数,这个新的函数就是他接受的函数固定了相应的参数,这个新的函数在使用时,只需输入原函数其余未固定的参数即可。
2. reduce
reduce:接受一个函数func(该函数两个输入参数),和一个序列,依次对序列里的值,执行函数操作。从左到右,func(func(func(0,1),2),3)…
3. * 和 ** 打包解包操作
在函数调用时解包,作为参数输入时是打包。*针对列表集合元组,**针对字典。
4. 装饰器及语法糖
自定义的函数装饰器,需要加wraps装饰来保存函数原始信息,如__doc__,name,签名等。如下图:
5. ,= 操作
a ,= [2]
b , = [2]
c , = (2,)
d , = {2}
e ,= range(2,3)
print(a,b,c,d,e)
# 2 2 2 2 2
只要可迭代对象内部仅有一个元素,就可以通过 ,= 的形式把这个值取出来,至于逗号和等号是否挨着无所谓。
,= 就是拆解列表,元组,集合,可迭代对象的特例,要求其只能有一个元素。
6. := 海象运算符
变量赋值是var = expr的形式,必须在它自己的行中写入,所以无论是创建列表还是读取文件,海象运算符允许您通过在另一个表达式的求值中运行不合规的变量赋值来缩短空间。
海象运算符只能在其他表达式中使用。
f = lambda x : x+2
data = [1,2,3,4]
f_data = [y for x in data if (y := f(x)) is not 4]
# [3, 5, 6]
等价于 f_data = [f(x) for x in data if f(x) is not 4],但运用 := 效率更高。
g = [y := f(3), y**2, y**3] #contents: [5, 25, 125]
y被定义为f(3),并且在同一表达式中紧跟其后使用。
def exponent(base,exp):
return base**exp
exponent(base=4, exp=(storage:=3))
用海象运算符,得到4的3次幂的值的同时,存储幂(3)的值。
再看一个例子:
f = lambda x : (m := x+1) + (m**2)
print(f(3)) # 20
7. np.dot(),np.multiply()
np的几个乘法总容易混,写在这里做个备忘。
np.dot(a, b),内积,即a的第一行乘以b的第一列,得到结果相加,作为输出结果的第一行第一列的值,后面以此类推。当然,在np数组中从0开始计数。a的最后一个shape要等于b的第一个shape,可以广播。大部分case等于 a @ b,np.matmul(a, b)。
而np.multiply(a,b) = a * b,两个矩阵的对应位置元素相乘,作为输出结果,可以广播。这个运算不需要满足a的最后一个shape要等于b的第一个shape,这个运算是可以交换a和b的位置的。
官方解释:
Dot product of two arrays. Specifically,
If both
a
andb
are 1-D arrays, it is inner product of vectors (without complex conjugation).If both
a
andb
are 2-D arrays, it is matrix multiplication, but using :func:matmul
ora @ b
is preferred.If either
a
orb
is 0-D (scalar), it is equivalent to :func:multiply
and usingnumpy.multiply(a, b)
ora * b
is
preferred.If
a
is an N-D array andb
is a 1-D array, it is a sum product over the last axis ofa
andb
.If
a
is an N-D array andb
is an M-D array (whereM>=2
), it is a sum product over the last axis ofa
and the second-to-last
axis ofb
::dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m])
8. glob
访问本地文件
>>> import glob
>>> glob.glob('./[0-9].*')
['./1.gif', './2.txt']
>>> glob.glob('*.gif')
['1.gif', 'card.gif']
>>> glob.glob('?.gif')
['1.gif']
>>> glob.glob('**/*.txt', recursive=True)
['2.txt', 'sub/3.txt']
>>> glob.glob('./**/', recursive=True)
['./', './sub/']