数值类型:
整型(int)-通常被称为是整型或整数,是正或负整数,不带数点。
长整型(long integers)-无限大小的整数,整数最后是一个大写或者小写的L
浮点型(floadting point real values)-浮点型由整数部分与小数部分组成,也可以使用科学计数法表示
复数(complex numbers)-复数的虚部以字母J或j结尾。如2+3i
1 int类型:
如:1, 78 , 99
class int(object):
"""
int(x=) -> int or long
int(x, base=) -> int or long Convert a number or string to an integer, or return if no arguments
are given. If x is floating point, the conversion truncates towards zero.
If x is outside the integer range, the function returns a long instead. If x is not a number or if base is given, then x must be a string or
Unicode object representing an integer literal in the given base. The
literal can be preceded by '+' or '-' and be surrounded by whitespace.
The base defaults to . Valid bases are and -. Base means to
interpret the base from the string as an integer literal.
>>> int('0b100', base=)
"""
def bit_length(self):
""" 返回表示该数字的时占用的最少位数 """
"""
int.bit_length() -> int Number of bits necessary to represent self in binary.
>>> bin()
'0b100101'
>>> ().bit_length()
"""
return def conjugate(self, *args, **kwargs): # real signature unknown
""" 返回该复数的共轭复数 """
""" Returns self, the complex conjugate of any int. """
pass def __abs__(self):
""" 返回绝对值 """
""" x.__abs__() <==> abs(x) """
pass def __add__(self, y):
""" x.__add__(y) <==> x+y """
pass def __and__(self, y):
""" x.__and__(y) <==> x&y """
pass def __cmp__(self, y):
""" 比较两个数大小 """
""" x.__cmp__(y) <==> cmp(x,y) """
pass def __coerce__(self, y):
""" 强制生成一个元组 """
""" x.__coerce__(y) <==> coerce(x, y) """
pass def __divmod__(self, y):
""" 相除,得到商和余数组成的元组 """
""" x.__divmod__(y) <==> divmod(x, y) """
pass def __div__(self, y):
""" x.__div__(y) <==> x/y """
pass def __float__(self):
""" 转换为浮点类型 """
""" x.__float__() <==> float(x) """
pass def __floordiv__(self, y):
""" x.__floordiv__(y) <==> x//y """
pass def __format__(self, *args, **kwargs): # real signature unknown
pass def __getattribute__(self, name):
""" x.__getattribute__('name') <==> x.name """
pass def __getnewargs__(self, *args, **kwargs): # real signature unknown
""" 内部调用 __new__方法或创建对象时传入参数使用 """
pass def __hash__(self):
"""如果对象object为哈希表类型,返回对象object的哈希值。哈希值为整数。在字典查找中,哈希值用于快速比较字典的键。两个数值如果相等,则哈希值也相等。"""
""" x.__hash__() <==> hash(x) """
pass def __hex__(self):
""" 返回当前数的 十六进制 表示 """
""" x.__hex__() <==> hex(x) """
pass def __index__(self):
""" 用于切片,数字无意义 """
""" x[y:z] <==> x[y.__index__():z.__index__()] """
pass def __init__(self, x, base=): # known special case of int.__init__
""" 构造方法,执行 x = 123 或 x = int(10) 时,自动调用,暂时忽略 """
"""
int(x=) -> int or long
int(x, base=) -> int or long Convert a number or string to an integer, or return if no arguments
are given. If x is floating point, the conversion truncates towards zero.
If x is outside the integer range, the function returns a long instead. If x is not a number or if base is given, then x must be a string or
Unicode object representing an integer literal in the given base. The
literal can be preceded by '+' or '-' and be surrounded by whitespace.
The base defaults to . Valid bases are and -. Base means to
interpret the base from the string as an integer literal.
>>> int('0b100', base=)
# (copied from class doc)
"""
pass def __int__(self):
""" 转换为整数 """
""" x.__int__() <==> int(x) """
pass def __invert__(self):
""" x.__invert__() <==> ~x """
pass def __long__(self):
""" 转换为长整数 """
""" x.__long__() <==> long(x) """
pass def __lshift__(self, y):
""" x.__lshift__(y) <==> x<<y """
pass def __mod__(self, y):
""" x.__mod__(y) <==> x%y """
pass def __mul__(self, y):
""" x.__mul__(y) <==> x*y """
pass def __neg__(self):
""" x.__neg__() <==> -x """
pass @staticmethod # known case of __new__
def __new__(S, *more):
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass def __nonzero__(self):
""" x.__nonzero__() <==> x != 0 """
pass def __oct__(self):
""" 返回改值的 八进制 表示 """
""" x.__oct__() <==> oct(x) """
pass def __or__(self, y):
""" x.__or__(y) <==> x|y """
pass def __pos__(self):
""" x.__pos__() <==> +x """
pass def __pow__(self, y, z=None):
""" 幂,次方 """
""" x.__pow__(y[, z]) <==> pow(x, y[, z]) """
pass def __radd__(self, y):
""" x.__radd__(y) <==> y+x """
pass def __rand__(self, y):
""" x.__rand__(y) <==> y&x """
pass def __rdivmod__(self, y):
""" x.__rdivmod__(y) <==> divmod(y, x) """
pass def __rdiv__(self, y):
""" x.__rdiv__(y) <==> y/x """
pass def __repr__(self):
"""转化为解释器可读取的形式 """
""" x.__repr__() <==> repr(x) """
pass def __str__(self):
"""转换为人阅读的形式,如果没有适于人阅读的解释形式的话,则返回解释器课阅读的形式"""
""" x.__str__() <==> str(x) """
pass def __rfloordiv__(self, y):
""" x.__rfloordiv__(y) <==> y//x """
pass def __rlshift__(self, y):
""" x.__rlshift__(y) <==> y<<x """
pass def __rmod__(self, y):
""" x.__rmod__(y) <==> y%x """
pass def __rmul__(self, y):
""" x.__rmul__(y) <==> y*x """
pass def __ror__(self, y):
""" x.__ror__(y) <==> y|x """
pass def __rpow__(self, x, z=None):
""" y.__rpow__(x[, z]) <==> pow(x, y[, z]) """
pass def __rrshift__(self, y):
""" x.__rrshift__(y) <==> y>>x """
pass def __rshift__(self, y):
""" x.__rshift__(y) <==> x>>y """
pass def __rsub__(self, y):
""" x.__rsub__(y) <==> y-x """
pass def __rtruediv__(self, y):
""" x.__rtruediv__(y) <==> y/x """
pass def __rxor__(self, y):
""" x.__rxor__(y) <==> y^x """
pass def __sub__(self, y):
""" x.__sub__(y) <==> x-y """
pass def __truediv__(self, y):
""" x.__truediv__(y) <==> x/y """
pass def __trunc__(self, *args, **kwargs):
""" 返回数值被截取为整形的值,在整形中无意义 """
pass def __xor__(self, y):
""" x.__xor__(y) <==> x^y """
pass denominator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
""" 分母 = 1 """
"""the denominator of a rational number in lowest terms""" imag = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
""" 虚数,无意义 """
"""the imaginary part of a complex number""" numerator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
""" 分子 = 数字大小 """
"""the numerator of a rational number in lowest terms""" real = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
""" 实属,无意义 """
"""the real part of a complex number"""
2.长整型
可能如:2147483649、9223372036854775807
int型过长时自动转换为长整型
class long(object):
"""
long(x=0) -> long
long(x, base=10) -> long Convert a number or string to a long integer, or return 0L if no arguments
are given. If x is floating point, the conversion truncates towards zero. If x is not a number or if base is given, then x must be a string or
Unicode object representing an integer literal in the given base. The
literal can be preceded by '+' or '-' and be surrounded by whitespace.
The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to
interpret the base from the string as an integer literal.
>>> int('0b100', base=0)
4L
"""
def bit_length(self): # real signature unknown; restored from __doc__
"""
long.bit_length() -> int or long Number of bits necessary to represent self in binary.
>>> bin(37L)
'0b100101'
>>> (37L).bit_length()
"""
return 0 def conjugate(self, *args, **kwargs): # real signature unknown
""" Returns self, the complex conjugate of any long. """
pass def __abs__(self): # real signature unknown; restored from __doc__
""" x.__abs__() <==> abs(x) """
pass def __add__(self, y): # real signature unknown; restored from __doc__
""" x.__add__(y) <==> x+y """
pass def __and__(self, y): # real signature unknown; restored from __doc__
""" x.__and__(y) <==> x&y """
pass def __cmp__(self, y): # real signature unknown; restored from __doc__
""" x.__cmp__(y) <==> cmp(x,y) """
pass def __coerce__(self, y): # real signature unknown; restored from __doc__
""" x.__coerce__(y) <==> coerce(x, y) """
pass def __divmod__(self, y): # real signature unknown; restored from __doc__
""" x.__divmod__(y) <==> divmod(x, y) """
pass def __div__(self, y): # real signature unknown; restored from __doc__
""" x.__div__(y) <==> x/y """
pass def __float__(self): # real signature unknown; restored from __doc__
""" x.__float__() <==> float(x) """
pass def __floordiv__(self, y): # real signature unknown; restored from __doc__
""" x.__floordiv__(y) <==> x//y """
pass def __format__(self, *args, **kwargs): # real signature unknown
pass def __getattribute__(self, name): # real signature unknown; restored from __doc__
""" x.__getattribute__('name') <==> x.name """
pass def __getnewargs__(self, *args, **kwargs): # real signature unknown
pass def __hash__(self): # real signature unknown; restored from __doc__
""" x.__hash__() <==> hash(x) """
pass def __hex__(self): # real signature unknown; restored from __doc__
""" x.__hex__() <==> hex(x) """
pass def __index__(self): # real signature unknown; restored from __doc__
""" x[y:z] <==> x[y.__index__():z.__index__()] """
pass def __init__(self, x=0): # real signature unknown; restored from __doc__
pass def __int__(self): # real signature unknown; restored from __doc__
""" x.__int__() <==> int(x) """
pass def __invert__(self): # real signature unknown; restored from __doc__
""" x.__invert__() <==> ~x """
pass def __long__(self): # real signature unknown; restored from __doc__
""" x.__long__() <==> long(x) """
pass def __lshift__(self, y): # real signature unknown; restored from __doc__
""" x.__lshift__(y) <==> x<<y """
pass def __mod__(self, y): # real signature unknown; restored from __doc__
""" x.__mod__(y) <==> x%y """
pass def __mul__(self, y): # real signature unknown; restored from __doc__
""" x.__mul__(y) <==> x*y """
pass def __neg__(self): # real signature unknown; restored from __doc__
""" x.__neg__() <==> -x """
pass @staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass def __nonzero__(self): # real signature unknown; restored from __doc__
""" x.__nonzero__() <==> x != 0 """
pass def __oct__(self): # real signature unknown; restored from __doc__
""" x.__oct__() <==> oct(x) """
pass def __or__(self, y): # real signature unknown; restored from __doc__
""" x.__or__(y) <==> x|y """
pass def __pos__(self): # real signature unknown; restored from __doc__
""" x.__pos__() <==> +x """
pass def __pow__(self, y, z=None): # real signature unknown; restored from __doc__
""" x.__pow__(y[, z]) <==> pow(x, y[, z]) """
pass def __radd__(self, y): # real signature unknown; restored from __doc__
""" x.__radd__(y) <==> y+x """
pass def __rand__(self, y): # real signature unknown; restored from __doc__
""" x.__rand__(y) <==> y&x """
pass def __rdivmod__(self, y): # real signature unknown; restored from __doc__
""" x.__rdivmod__(y) <==> divmod(y, x) """
pass def __rdiv__(self, y): # real signature unknown; restored from __doc__
""" x.__rdiv__(y) <==> y/x """
pass def __repr__(self): # real signature unknown; restored from __doc__
""" x.__repr__() <==> repr(x) """
pass def __rfloordiv__(self, y): # real signature unknown; restored from __doc__
""" x.__rfloordiv__(y) <==> y//x """
pass def __rlshift__(self, y): # real signature unknown; restored from __doc__
""" x.__rlshift__(y) <==> y<<x """
pass def __rmod__(self, y): # real signature unknown; restored from __doc__
""" x.__rmod__(y) <==> y%x """
pass def __rmul__(self, y): # real signature unknown; restored from __doc__
""" x.__rmul__(y) <==> y*x """
pass def __ror__(self, y): # real signature unknown; restored from __doc__
""" x.__ror__(y) <==> y|x """
pass def __rpow__(self, x, z=None): # real signature unknown; restored from __doc__
""" y.__rpow__(x[, z]) <==> pow(x, y[, z]) """
pass def __rrshift__(self, y): # real signature unknown; restored from __doc__
""" x.__rrshift__(y) <==> y>>x """
pass def __rshift__(self, y): # real signature unknown; restored from __doc__
""" x.__rshift__(y) <==> x>>y """
pass def __rsub__(self, y): # real signature unknown; restored from __doc__
""" x.__rsub__(y) <==> y-x """
pass def __rtruediv__(self, y): # real signature unknown; restored from __doc__
""" x.__rtruediv__(y) <==> y/x """
pass def __rxor__(self, y): # real signature unknown; restored from __doc__
""" x.__rxor__(y) <==> y^x """
pass def __sizeof__(self, *args, **kwargs): # real signature unknown
""" Returns size in memory, in bytes """
pass def __str__(self): # real signature unknown; restored from __doc__
""" x.__str__() <==> str(x) """
pass def __sub__(self, y): # real signature unknown; restored from __doc__
""" x.__sub__(y) <==> x-y """
pass def __truediv__(self, y): # real signature unknown; restored from __doc__
""" x.__truediv__(y) <==> x/y """
pass def __trunc__(self, *args, **kwargs): # real signature unknown
""" Truncating an Integral returns itself. """
pass def __xor__(self, y): # real signature unknown; restored from __doc__
""" x.__xor__(y) <==> x^y """
pass denominator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""the denominator of a rational number in lowest terms""" imag = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""the imaginary part of a complex number""" numerator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""the numerator of a rational number in lowest terms""" real = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""the real part of a complex number""" long
3.浮点
如:3.123434
class float(object):
"""
float(x) -> floating point number Convert a string or number to a floating point number, if possible.
"""
def as_integer_ratio(self):
""" 获取改值的最简比 """
"""
float.as_integer_ratio() -> (int, int) Return a pair of integers, whose ratio is exactly equal to the original
float and with a positive denominator.
Raise OverflowError on infinities and a ValueError on NaNs. >>> (10.0).as_integer_ratio()
(10, 1)
>>> (0.0).as_integer_ratio()
(0, 1)
>>> (-.25).as_integer_ratio()
(-1, 4)
"""
pass def conjugate(self, *args, **kwargs): # real signature unknown
""" Return self, the complex conjugate of any float. """
pass def fromhex(self, string):
""" 将十六进制字符串转换成浮点型 """
"""
float.fromhex(string) -> float Create a floating-point number from a hexadecimal string.
>>> float.fromhex('0x1.ffffp10')
2047.984375
>>> float.fromhex('-0x1p-1074')
-4.9406564584124654e-324
"""
return 0.0 def hex(self):
""" 返回当前值的 16 进制表示 """
"""
float.hex() -> string Return a hexadecimal representation of a floating-point number.
>>> (-0.1).hex()
'-0x1.999999999999ap-4'
>>> 3.14159.hex()
'0x1.921f9f01b866ep+1'
"""
return "" def is_integer(self, *args, **kwargs): # real signature unknown
""" Return True if the float is an integer. """
pass def __abs__(self):
""" x.__abs__() <==> abs(x) """
pass def __add__(self, y):
""" x.__add__(y) <==> x+y """
pass def __coerce__(self, y):
""" x.__coerce__(y) <==> coerce(x, y) """
pass def __divmod__(self, y):
""" x.__divmod__(y) <==> divmod(x, y) """
pass def __div__(self, y):
""" x.__div__(y) <==> x/y """
pass def __eq__(self, y):
""" x.__eq__(y) <==> x==y """
pass def __float__(self):
""" x.__float__() <==> float(x) """
pass def __floordiv__(self, y):
""" x.__floordiv__(y) <==> x//y """
pass def __format__(self, format_spec):
"""
float.__format__(format_spec) -> string Formats the float according to format_spec.
"""
return "" def __getattribute__(self, name):
""" x.__getattribute__('name') <==> x.name """
pass def __getformat__(self, typestr):
"""
float.__getformat__(typestr) -> string You probably don't want to use this function. It exists mainly to be
used in Python's test suite. typestr must be 'double' or 'float'. This function returns whichever of
'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the
format of floating point numbers used by the C type named by typestr.
"""
return "" def __getnewargs__(self, *args, **kwargs): # real signature unknown
pass def __ge__(self, y):
""" x.__ge__(y) <==> x>=y """
pass def __gt__(self, y):
""" x.__gt__(y) <==> x>y """
pass def __hash__(self):
""" x.__hash__() <==> hash(x) """
pass def __init__(self, x):
pass def __int__(self):
""" x.__int__() <==> int(x) """
pass def __le__(self, y):
""" x.__le__(y) <==> x<=y """
pass def __long__(self):
""" x.__long__() <==> long(x) """
pass def __lt__(self, y):
""" x.__lt__(y) <==> x<y """
pass def __mod__(self, y):
""" x.__mod__(y) <==> x%y """
pass def __mul__(self, y):
""" x.__mul__(y) <==> x*y """
pass def __neg__(self):
""" x.__neg__() <==> -x """
pass @staticmethod # known case of __new__
def __new__(S, *more):
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass def __ne__(self, y):
""" x.__ne__(y) <==> x!=y """
pass def __nonzero__(self):
""" x.__nonzero__() <==> x != 0 """
pass def __pos__(self):
""" x.__pos__() <==> +x """
pass def __pow__(self, y, z=None):
""" x.__pow__(y[, z]) <==> pow(x, y[, z]) """
pass def __radd__(self, y):
""" x.__radd__(y) <==> y+x """
pass def __rdivmod__(self, y):
""" x.__rdivmod__(y) <==> divmod(y, x) """
pass def __rdiv__(self, y):
""" x.__rdiv__(y) <==> y/x """
pass def __repr__(self):
""" x.__repr__() <==> repr(x) """
pass def __rfloordiv__(self, y):
""" x.__rfloordiv__(y) <==> y//x """
pass def __rmod__(self, y):
""" x.__rmod__(y) <==> y%x """
pass def __rmul__(self, y):
""" x.__rmul__(y) <==> y*x """
pass def __rpow__(self, x, z=None):
""" y.__rpow__(x[, z]) <==> pow(x, y[, z]) """
pass def __rsub__(self, y):
""" x.__rsub__(y) <==> y-x """
pass def __rtruediv__(self, y):
""" x.__rtruediv__(y) <==> y/x """
pass def __setformat__(self, typestr, fmt):
"""
float.__setformat__(typestr, fmt) -> None You probably don't want to use this function. It exists mainly to be
used in Python's test suite. typestr must be 'double' or 'float'. fmt must be one of 'unknown',
'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be
one of the latter two if it appears to match the underlying C reality. Override the automatic determination of C-level floating point type.
This affects how floats are converted to and from binary strings.
"""
pass def __str__(self):
""" x.__str__() <==> str(x) """
pass def __sub__(self, y):
""" x.__sub__(y) <==> x-y """
pass def __truediv__(self, y):
""" x.__truediv__(y) <==> x/y """
pass def __trunc__(self, *args, **kwargs): # real signature unknown
""" Return the Integral closest to x between 0 and x. """
pass imag = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""the imaginary part of a complex number""" real = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""the real part of a complex number"""
Python数字类型转换
int(x [,base ]) 将x转换为一个整数
long(x [,base ]) 将x转换为一个长整数
float(x ) 将x转换到一个浮点数
complex(real [,imag ]) 创建一个复数
str(x ) 将对象 x 转换为字符串
repr(x ) 将对象 x 转换为表达式字符串
eval(str ) 用来计算在字符串中的有效Python表达式,并返回一个对象
tuple(s ) 将序列 s 转换为一个元组
list(s ) 将序列 s 转换为一个列表
chr(x ) 将一个整数转换为一个字符
unichr(x ) 将一个整数转换为Unicode字符
ord(x ) 将一个字符转换为它的整数值
hex(x ) 将一个整数转换为一个十六进制字符串
oct(x ) 将一个整数转换为一个八进制字符串
函数 返回值 ( 描述 )
abs(x) 返回数字的绝对值,如abs(-10) 返回 10
ceil(x) 返回数字的上入整数,如math.ceil(4.1) 返回 5
cmp(x, y) 如果 x < y 返回 -1, 如果 x == y 返回 0, 如果 x > y 返回 1
exp(x) 返回e的x次幂(ex),如math.exp(1) 返回2.718281828459045
fabs(x) 返回数字的绝对值,如math.fabs(-10) 返回10.0
floor(x) 返回数字的下舍整数,如math.floor(4.9)返回 4
log(x) 如math.log(math.e)返回1.0,math.log(100,10)返回2.0
log10(x) 返回以10为基数的x的对数,如math.log10(100)返回 2.0
max(x1, x2,...) 返回给定参数的最大值,参数可以为序列。
min(x1, x2,...) 返回给定参数的最小值,参数可以为序列。
modf(x) 返回x的整数部分与小数部分,两部分的数值符号与x相同,整数部分以浮点型表示。
pow(x, y) x**y 运算后的值。
round(x [,n]) 返回浮点数x的四舍五入值,如给出n值,则代表舍入到小数点后的位数。
sqrt(x) 返回数字x的平方根,数字可以为负数,返回类型为实数,如math.sqrt(4)返回 2+0j
随机数函数:
函数 描述
choice(seq) 从序列的元素中随机挑选一个元素,比如random.choice(range(10)),从0到9中随机挑选一个整数。
randrange ([start,] stop [,step]) 从指定范围内,按指定基数递增的集合中获取一个随机数,基数缺省值为1
random() 随机生成下一个实数,它在[0,1)范围内。
seed([x]) 改变随机数生成器的种子seed。如果你不了解其原理,你不必特别去设定seed,Python会帮你选择seed。
shuffle(lst) 将序列的所有元素随机排序
uniform(x, y) 随机生成下一个实数,它在[x,y]范围内。
Python算术运算符
以下假设变量a为10,变量b为20:
运算符 描述 实例
+ 加 - 两个对象相加 a + b 输出结果 30
- 减 - 得到负数或是一个数减去另一个数 a - b 输出结果 -10
* 乘 - 两个数相乘或是返回一个被重复若干次的字符串 a * b 输出结果 200
/ 除 - x除以y b / a 输出结果 2
% 取模 - 返回除法的余数 b % a 输出结果 0
** 幂 - 返回x的y次幂 a**b 为10的20次方, 输出结果 100000000000000000000
// 取整除 - 返回商的整数部分 9//2 输出结果 4 , 9.0//2.0 输出结果 4.0
Python比较运算符
以下假设变量a为10,变量b为20:
运算符 描述 实例
== 等于 - 比较对象是否相等 (a == b) 返回 False。
!= 不等于 - 比较两个对象是否不相等 (a != b) 返回 true.
<> 不等于 - 比较两个对象是否不相等 (a <> b) 返回 true。这个运算符类似 != 。
> 大于 - 返回x是否大于y (a > b) 返回 False。
< 小于 - 返回x是否小于y。所有比较运算符返回1表示真,返回0表示假。这分别与特殊的变量True和False等价。注意,这些变量名的大写。 (a < b) 返回 true。
>= 大于等于 - 返回x是否大于等于y。 (a >= b) 返回 False。
<= 小于等于 - 返回x是否小于等于y。 (a <= b) 返回 true。
Python赋值运算符
以下假设变量a为10,变量b为20:
运算符 描述 实例
= 简单的赋值运算符 c = a + b 将 a + b 的运算结果赋值为 c
+= 加法赋值运算符 c += a 等效于 c = c + a
-= 减法赋值运算符 c -= a 等效于 c = c - a
*= 乘法赋值运算符 c *= a 等效于 c = c * a
/= 除法赋值运算符 c /= a 等效于 c = c / a
%= 取模赋值运算符 c %= a 等效于 c = c % a
**= 幂赋值运算符 c **= a 等效于 c = c ** a
//= 取整除赋值运算符 c //= a 等效于 c = c // a
数字的四舍五入
对于简单的舍入运算,使用内置的 round(value, ndigits) 函数即可。比如:
>>> round(1.23, 1)
1.2
>>> round(1.27, 1)
1.3
>>> round(-1.27, 1)
-1.3
>>> round(1.25361,3)
1.254
>>>
当一个值刚好在两个边界的中间的时候, round 函数返回离它最近的偶数。也就是说,对 1.5 或者 2.5 的舍入运算都会得到 2
不要将舍入和格式化输出搞混淆了。如果你的目的只是简单的输出一定宽度的数,你不需要使用 round() 函数。而仅仅只需要在格式化的时候指定精度即可。比如:
>>> x = 1.23456
>>> format(x, '0.2f')
'1.23'
>>> format(x, '0.3f')
'1.235'
>>> 'value is {:0.3f}'.format(x)
'value is 1.235'
>>>
在计算的时候会有一点点小的误差,但是这些小的误差是能被理解与容忍的。如果不能允许这样的小误差 (比如涉及到金融领域),那么就得考虑使用 decimal 模块了
数字的格式化输出
格式化输出单个数字的时候,可以使用内置的 format() 函数,比如:
>>> x = 1234.56789
5.3. 3.3 数字的格式化输出
>>> format(x, '0.2f')
'1234.57'
在很多 Python 代码中会看到使用% 来格式化数字的,比如:
>>> '%0.2f' % x
'1234.57'
>>> '%10.1f' % x
' 1234.6'
>>> '%-10.1f' % x
'1234.6 '
>>>
这种格式化方法也是可行的,不过比更加先进的 format() 要差一点。
转换或者输出使用二进制,八进制或十六进制表示的整数
为了将整数转换为二进制、八进制或十六进制的文本串,可以分别使用 bin() ,
oct() 或 hex() 函数:
>>> x = 1234
>>> bin(x)
'0b10011010010'
>>> oct(x)
'0o2322'
>>> hex(x)
'0x4d2'
>>>
另外,如果你不想输出 0b , 0o 或者 0x 的前缀的话,可以使用 format() 函数。比如:
>>> format(x, 'b')
'10011010010'
>>> format(x, 'o')
'2322'
>>> format(x, 'x')
'4d2'
>>>
为了以不同的进制转换整数字符串,简单的使用带有进制的 int() 函数即可:
>>> int('4d2', 16)
1234
>>> int('10011010010', 2)
1234
>>>
分数运算
fractions 模块可以被用来执行包含分数的数学运算。比如:
>>> from fractions import Fraction
>>> a = Fraction(5, 4)
>>> b = Fraction(7, 16)
>>> print(a + b)
27/16
>>> print(a * b)
35/64
>>> c = a * b
>>> c.numerator
35
>>> c.denominator
64
>>> float(c)
0.546875
>>> print(c.limit_denominator(8))
4/7
>>> x = 3.75
>>> y = Fraction(*x.as_integer_ratio())
>>> y
Fraction(15, 4)
>>>
大型数组运算
涉及到数组的重量级运算操作,可以使用 NumPy 库。 NumPy 的一个主要特征是它会给 Python 提供一个数组对象,相比标准的 Python 列表而已更适合用来做数学运算。下面是一个简单的小例子,向你展示标准列表对象和 NumPy 数组对象之间的差别:
>>> x = [1, 2, 3, 4]
>>> y = [5, 6, 7, 8]
>>> x * 2
[1, 2, 3, 4, 1, 2, 3, 4]
>>> x + 10
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "int") to list
>>> x + y
[1, 2, 3, 4, 5, 6, 7, 8]
>>> import numpy as np
>>> ax = np.array([1, 2, 3, 4])
>>> ay = np.array([5, 6, 7, 8])
>>> ax * 2
array([2, 4, 6, 8])
>>> ax + 10
array([11, 12, 13, 14])
>>> ax + ay
array([ 6, 8, 10, 12])
>>> ax * ay
array([ 5, 12, 21, 32])
>>>
正如所见,两种方案中数组的基本数学运算结果并不相同。特别的, NumPy 中的标量运算 (比如 ax * 2 或 ax + 10 ) 会作用在每一个元素上。另外,当两个操作数都是数组的时候执行元素对等位置计算,并最终生成一个新的数组。
对整个数组中所有元素同时执行数学运算可以使得作用在整个数组上的函数运算简单而又快速。比如,如果你想计算多项式的值,可以这样做:
>>> def f(x):
... return 3*x**2 - 2*x + 7
...
>>> f(ax)
array([ 8, 15, 28, 47])
>>>
随机选择
random 模块有大量的函数用来产生随机数和随机选择元素。比如,要想从一个序列中随机的抽取一个元素,可以使用 random.choice() :
>>> import random
>>> values = [1, 2, 3, 4, 5, 6]
>>> random.choice(values)
2
>>> random.choice(values)
3
>>>
为了提取出 N 个不同元素的样本用来做进一步的操作,可以使用 random.sample():
>>> random.sample(values, 2)
[6, 2]
>>> random.sample(values, 2)
[4, 3]
>>> random.sample(values, 3)
[4, 3, 1]
如果你仅仅只是想打乱序列中元素的顺序,可以使用 random.shuffle() :
>>> random.shuffle(values)
>>> values
[2, 4, 6, 5, 3, 1]
>>> random.shuffle(values)
>>> values
[3, 5, 2, 1, 6, 4]
>>>
生成随机整数,请使用 random.randint() :
>>> random.randint(0,10)
2
>>> random.randint(0,10)
5
>>> random.randint(0,10)
0
为了生成 0 到 1 范围内均匀分布的浮点数,使用 random.random() :
>>> random.random()
0.9406677561675867
>>> random.random()
0.133129581343897
>>> random.random()
0.4144991136919316
>>>