数学运算
len(s)
返回对象内元素的个数:
In [83]: dic = {'a':1,'b':3}
In [84]: len(dic)
Out[84]: 2
max(iterable,*[, key, default])
返回最大值:
In [99]: max(3,1,4,2,1)
Out[99]: 4
In [100]: max((),default=0)
Out[100]: 0
In [89]: di = {'a':3,'b1':1,'c':4}
In [90]: max(di)
Out[90]: 'c'
In [102]: a = [{'name':'xiaoming','age':18,'gender':'male'},{'name':'
...: xiaohong','age':20,'gender':'female'}]
In [104]: max(a,key=lambda x: x['age'])
Out[104]: {'name': 'xiaohong', 'age': 20, 'gender': 'female'}
如果已知多个列表,找出列表更长的,使用 max 方法:
In [12]: def max_length(*lst):
...: return max(*lst, key=lambda v: len(v))
In [13]: max_length([1, 2, 3], [4, 5, 6, 7], [8])
Out[13]: [4, 5, 6, 7]
max 有一个 default 参数:
- 当传入的列表为空时,若参数 default 被赋值,则返回 default;
- 否则,会抛空序列的异常(empty sequence)。
In [4]: max([],default='0')
Out[4]: '0'
In [5]: max([])
ValueError: max() arg is an empty sequence
pow(x, y, z=None, /)
x 为底的 y 次幂,如果 z 给出,取余:
In [149]: pow(3, 2, 4)
Out[149]: 1
round(number[, ndigits])
四舍五入,ndigits 代表小数点后保留几位:
In [157]: round(10.0222222, 3)
Out[157]: 10.022
sum(iterable, /, start=0)
求和:
In [181]: a = [1,4,2,3,1]
In [182]: sum(a)
Out[182]: 11
In [185]: sum(a,10) #求和的初始值为10
Out[185]: 21
abs(x, /)
求绝对值或复数的模:
In [1]: abs(-6)
Out[1]: 6
divmod(a,b)
分别取商和余数:
In [97]: divmod(10,3)
Out[97]: (3, 1)
complex([real[, imag]])
创建一个复数:
In [81]: complex(1,2)
Out[81]: (1+2j)
hash(object)
返回对象的哈希值:
In [30]: class Student():
...: def __init__(self,id,name):
...: self.id = id
...: self.name = name
...: def __repr__(self):
...: return 'id = '+self.id +', name = '+self.name
In [33]: xiaoming = Student('001','xiaoming')
In [112]: hash(xiaoming)
Out[112]: 6139638
id(object)
返回对象的内存地址:
In [30]: class Student():
...: def __init__(self,id,name):
...: self.id = id
...: self.name = name
...: def __repr__(self):
...: return 'id = '+self.id +', name = '+self.name
In [33]: xiaoming = Student('001','xiaoming')
In [115]: id(xiaoming)
Out[115]: 98234208