1 math.ceil() #向上取整
math.floor() #向下取整
round(a,2) #a四舍五入,保留2位小数
int() #向下取整 ,返回整数类型
math.sqrt() #开根号
pow(a,x) #求a的x次方
2 遍历字典
https://www.cnblogs.com/stuqx/p/7291948.html
3 字典根据value进行简单的排序
d = {'a':1,'b':4,'c':2} a=sorted(d.items(),key = lambda x:x[1],reverse = True) print(a)
输出:[('b', 4), ('c', 2), ('a', 1)]
4 复杂list排序
students = [('john', 'W', 1), ('jane', 'B', 12), ('dave', 'B', 1)] a=sorted(students, key=operator.itemgetter(1,2)) print(a)输出:[('dave', 'B', 1), ('jane', 'B', 12), ('john', 'W', 1)]
5 排列、组合
from itertools import permutations from itertools import combinations for i in permutations([1, 2, 3], 3): print(i) for i in combinations([1, 2, 3], 2): print(i)
输出:(1, 2, 3)
(1, 3, 2)(2, 1, 3)
(2, 3, 1)
(3, 1, 2)
(3, 2, 1)
(1, 2)
(1, 3)
(2, 3)
注意返回类型:
a=permutations([1, 2, 3]) print(type(a)) print(list(a))
输出:
<class 'itertools.permutations'>
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
6 注意numpy广播机制
a = np.random.randn(2, 3) # a.shape = (2, 3) b = np.random.randn(2, 1) # b.shape = (2, 1) print(a) print(b) c = a + b print(c) aaa=[1,2] bbb=[4,3] print(aaa+bbb)
输出:
[[ 0.22439514 -1.46048723 -0.09989994]
[-0.16181647 0.89533506 -0.02419727]]
[[-1.98479857]
[-0.45767346]]
[[-1.76040344 -3.4452858 -2.08469852]
[-0.61948993 0.4376616 -0.48187073]]
[1, 2, 4, 3]
a = np.random.randn(3, 3) b = np.random.randn(3, 1) c = a*b print(c)
输出
[[ 0.31930559 0.57259555 0.3371194 ]
[-0.55700812 -0.49222884 0.57338674]
[-0.67481986 -0.16179442 1.52381768]]