python 数字类型
数值类型:
整型(int)-通常被称为是整型或整数,是正或负整数,不带数点。
长整型(long integers)-无限大小的整数,整数最后是一个大写或者小写的L
浮点型(floadting point real values)-浮点型由整数部分与小数部分组成,也可以使用科学计数法表示
复数(complex numbers)-复数的虚部以字母J或j结尾。如2+3i
1 int类型:
如:1, 78 , 99
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 class int(object): 2 """ 3 int(x=0) -> int or long 4 int(x, base=10) -> int or long 5 6 Convert a number or string to an integer, or return 0 if no arguments 7 are given. If x is floating point, the conversion truncates towards zero. 8 If x is outside the integer range, the function returns a long instead. 9 10 If x is not a number or if base is given, then x must be a string or 11 Unicode object representing an integer literal in the given base. The 12 literal can be preceded by '+' or '-' and be surrounded by whitespace. 13 The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to 14 interpret the base from the string as an integer literal. 15 >>> int('0b100', base=0) 16 """ 17 def bit_length(self): 18 """ 返回表示该数字的时占用的最少位数 """ 19 """ 20 int.bit_length() -> int 21 22 Number of bits necessary to represent self in binary. 23 >>> bin(37) 24 '0b100101' 25 >>> (37).bit_length() 26 """ 27 return 0 28 29 def conjugate(self, *args, **kwargs): # real signature unknown 30 """ 返回该复数的共轭复数 """ 31 """ Returns self, the complex conjugate of any int. """ 32 pass 33 34 def __abs__(self): 35 """ 返回绝对值 """ 36 """ x.__abs__() <==> abs(x) """ 37 pass 38 39 def __add__(self, y): 40 """ x.__add__(y) <==> x+y """ 41 pass 42 43 def __and__(self, y): 44 """ x.__and__(y) <==> x&y """ 45 pass 46 47 def __cmp__(self, y): 48 """ 比较两个数大小 """ 49 """ x.__cmp__(y) <==> cmp(x,y) """ 50 pass 51 52 def __coerce__(self, y): 53 """ 强制生成一个元组 """ 54 """ x.__coerce__(y) <==> coerce(x, y) """ 55 pass 56 57 def __divmod__(self, y): 58 """ 相除,得到商和余数组成的元组 """ 59 """ x.__divmod__(y) <==> divmod(x, y) """ 60 pass 61 62 def __div__(self, y): 63 """ x.__div__(y) <==> x/y """ 64 pass 65 66 def __float__(self): 67 """ 转换为浮点类型 """ 68 """ x.__float__() <==> float(x) """ 69 pass 70 71 def __floordiv__(self, y): 72 """ x.__floordiv__(y) <==> x//y """ 73 pass 74 75 def __format__(self, *args, **kwargs): # real signature unknown 76 pass 77 78 def __getattribute__(self, name): 79 """ x.__getattribute__('name') <==> x.name """ 80 pass 81 82 def __getnewargs__(self, *args, **kwargs): # real signature unknown 83 """ 内部调用 __new__方法或创建对象时传入参数使用 """ 84 pass 85 86 def __hash__(self): 87 """如果对象object为哈希表类型,返回对象object的哈希值。哈希值为整数。在字典查找中,哈希值用于快速比较字典的键。两个数值如果相等,则哈希值也相等。""" 88 """ x.__hash__() <==> hash(x) """ 89 pass 90 91 def __hex__(self): 92 """ 返回当前数的 十六进制 表示 """ 93 """ x.__hex__() <==> hex(x) """ 94 pass 95 96 def __index__(self): 97 """ 用于切片,数字无意义 """ 98 """ x[y:z] <==> x[y.__index__():z.__index__()] """ 99 pass 100 101 def __init__(self, x, base=10): # known special case of int.__init__ 102 """ 构造方法,执行 x = 123 或 x = int(10) 时,自动调用,暂时忽略 """ 103 """ 104 int(x=0) -> int or long 105 int(x, base=10) -> int or long 106 107 Convert a number or string to an integer, or return 0 if no arguments 108 are given. If x is floating point, the conversion truncates towards zero. 109 If x is outside the integer range, the function returns a long instead. 110 111 If x is not a number or if base is given, then x must be a string or 112 Unicode object representing an integer literal in the given base. The 113 literal can be preceded by '+' or '-' and be surrounded by whitespace. 114 The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to 115 interpret the base from the string as an integer literal. 116 >>> int('0b100', base=0) 117 # (copied from class doc) 118 """ 119 pass 120 121 def __int__(self): 122 """ 转换为整数 """ 123 """ x.__int__() <==> int(x) """ 124 pass 125 126 def __invert__(self): 127 """ x.__invert__() <==> ~x """ 128 pass 129 130 def __long__(self): 131 """ 转换为长整数 """ 132 """ x.__long__() <==> long(x) """ 133 pass 134 135 def __lshift__(self, y): 136 """ x.__lshift__(y) <==> x<<y """ 137 pass 138 139 def __mod__(self, y): 140 """ x.__mod__(y) <==> x%y """ 141 pass 142 143 def __mul__(self, y): 144 """ x.__mul__(y) <==> x*y """ 145 pass 146 147 def __neg__(self): 148 """ x.__neg__() <==> -x """ 149 pass 150 151 @staticmethod # known case of __new__ 152 def __new__(S, *more): 153 """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ 154 pass 155 156 def __nonzero__(self): 157 """ x.__nonzero__() <==> x != 0 """ 158 pass 159 160 def __oct__(self): 161 """ 返回改值的 八进制 表示 """ 162 """ x.__oct__() <==> oct(x) """ 163 pass 164 165 def __or__(self, y): 166 """ x.__or__(y) <==> x|y """ 167 pass 168 169 def __pos__(self): 170 """ x.__pos__() <==> +x """ 171 pass 172 173 def __pow__(self, y, z=None): 174 """ 幂,次方 """ 175 """ x.__pow__(y[, z]) <==> pow(x, y[, z]) """ 176 pass 177 178 def __radd__(self, y): 179 """ x.__radd__(y) <==> y+x """ 180 pass 181 182 def __rand__(self, y): 183 """ x.__rand__(y) <==> y&x """ 184 pass 185 186 def __rdivmod__(self, y): 187 """ x.__rdivmod__(y) <==> divmod(y, x) """ 188 pass 189 190 def __rdiv__(self, y): 191 """ x.__rdiv__(y) <==> y/x """ 192 pass 193 194 def __repr__(self): 195 """转化为解释器可读取的形式 """ 196 """ x.__repr__() <==> repr(x) """ 197 pass 198 199 def __str__(self): 200 """转换为人阅读的形式,如果没有适于人阅读的解释形式的话,则返回解释器课阅读的形式""" 201 """ x.__str__() <==> str(x) """ 202 pass 203 204 def __rfloordiv__(self, y): 205 """ x.__rfloordiv__(y) <==> y//x """ 206 pass 207 208 def __rlshift__(self, y): 209 """ x.__rlshift__(y) <==> y<<x """ 210 pass 211 212 def __rmod__(self, y): 213 """ x.__rmod__(y) <==> y%x """ 214 pass 215 216 def __rmul__(self, y): 217 """ x.__rmul__(y) <==> y*x """ 218 pass 219 220 def __ror__(self, y): 221 """ x.__ror__(y) <==> y|x """ 222 pass 223 224 def __rpow__(self, x, z=None): 225 """ y.__rpow__(x[, z]) <==> pow(x, y[, z]) """ 226 pass 227 228 def __rrshift__(self, y): 229 """ x.__rrshift__(y) <==> y>>x """ 230 pass 231 232 def __rshift__(self, y): 233 """ x.__rshift__(y) <==> x>>y """ 234 pass 235 236 def __rsub__(self, y): 237 """ x.__rsub__(y) <==> y-x """ 238 pass 239 240 def __rtruediv__(self, y): 241 """ x.__rtruediv__(y) <==> y/x """ 242 pass 243 244 def __rxor__(self, y): 245 """ x.__rxor__(y) <==> y^x """ 246 pass 247 248 def __sub__(self, y): 249 """ x.__sub__(y) <==> x-y """ 250 pass 251 252 def __truediv__(self, y): 253 """ x.__truediv__(y) <==> x/y """ 254 pass 255 256 def __trunc__(self, *args, **kwargs): 257 """ 返回数值被截取为整形的值,在整形中无意义 """ 258 pass 259 260 def __xor__(self, y): 261 """ x.__xor__(y) <==> x^y """ 262 pass 263 264 denominator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 265 """ 分母 = 1 """ 266 """the denominator of a rational number in lowest terms""" 267 268 imag = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 269 """ 虚数,无意义 """ 270 """the imaginary part of a complex number""" 271 272 numerator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 273 """ 分子 = 数字大小 """ 274 """the numerator of a rational number in lowest terms""" 275 276 real = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 277 """ 实属,无意义 """ 278 """the real part of a complex number"""
2.长整型
可能如:2147483649、9223372036854775807
int型过长时自动转换为长整型
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 class long(object): 2 """ 3 long(x=0) -> long 4 long(x, base=10) -> long 5 6 Convert a number or string to a long integer, or return 0L if no arguments 7 are given. If x is floating point, the conversion truncates towards zero. 8 9 If x is not a number or if base is given, then x must be a string or 10 Unicode object representing an integer literal in the given base. The 11 literal can be preceded by '+' or '-' and be surrounded by whitespace. 12 The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to 13 interpret the base from the string as an integer literal. 14 >>> int('0b100', base=0) 15 4L 16 """ 17 def bit_length(self): # real signature unknown; restored from __doc__ 18 """ 19 long.bit_length() -> int or long 20 21 Number of bits necessary to represent self in binary. 22 >>> bin(37L) 23 '0b100101' 24 >>> (37L).bit_length() 25 """ 26 return 0 27 28 def conjugate(self, *args, **kwargs): # real signature unknown 29 """ Returns self, the complex conjugate of any long. """ 30 pass 31 32 def __abs__(self): # real signature unknown; restored from __doc__ 33 """ x.__abs__() <==> abs(x) """ 34 pass 35 36 def __add__(self, y): # real signature unknown; restored from __doc__ 37 """ x.__add__(y) <==> x+y """ 38 pass 39 40 def __and__(self, y): # real signature unknown; restored from __doc__ 41 """ x.__and__(y) <==> x&y """ 42 pass 43 44 def __cmp__(self, y): # real signature unknown; restored from __doc__ 45 """ x.__cmp__(y) <==> cmp(x,y) """ 46 pass 47 48 def __coerce__(self, y): # real signature unknown; restored from __doc__ 49 """ x.__coerce__(y) <==> coerce(x, y) """ 50 pass 51 52 def __divmod__(self, y): # real signature unknown; restored from __doc__ 53 """ x.__divmod__(y) <==> divmod(x, y) """ 54 pass 55 56 def __div__(self, y): # real signature unknown; restored from __doc__ 57 """ x.__div__(y) <==> x/y """ 58 pass 59 60 def __float__(self): # real signature unknown; restored from __doc__ 61 """ x.__float__() <==> float(x) """ 62 pass 63 64 def __floordiv__(self, y): # real signature unknown; restored from __doc__ 65 """ x.__floordiv__(y) <==> x//y """ 66 pass 67 68 def __format__(self, *args, **kwargs): # real signature unknown 69 pass 70 71 def __getattribute__(self, name): # real signature unknown; restored from __doc__ 72 """ x.__getattribute__('name') <==> x.name """ 73 pass 74 75 def __getnewargs__(self, *args, **kwargs): # real signature unknown 76 pass 77 78 def __hash__(self): # real signature unknown; restored from __doc__ 79 """ x.__hash__() <==> hash(x) """ 80 pass 81 82 def __hex__(self): # real signature unknown; restored from __doc__ 83 """ x.__hex__() <==> hex(x) """ 84 pass 85 86 def __index__(self): # real signature unknown; restored from __doc__ 87 """ x[y:z] <==> x[y.__index__():z.__index__()] """ 88 pass 89 90 def __init__(self, x=0): # real signature unknown; restored from __doc__ 91 pass 92 93 def __int__(self): # real signature unknown; restored from __doc__ 94 """ x.__int__() <==> int(x) """ 95 pass 96 97 def __invert__(self): # real signature unknown; restored from __doc__ 98 """ x.__invert__() <==> ~x """ 99 pass 100 101 def __long__(self): # real signature unknown; restored from __doc__ 102 """ x.__long__() <==> long(x) """ 103 pass 104 105 def __lshift__(self, y): # real signature unknown; restored from __doc__ 106 """ x.__lshift__(y) <==> x<<y """ 107 pass 108 109 def __mod__(self, y): # real signature unknown; restored from __doc__ 110 """ x.__mod__(y) <==> x%y """ 111 pass 112 113 def __mul__(self, y): # real signature unknown; restored from __doc__ 114 """ x.__mul__(y) <==> x*y """ 115 pass 116 117 def __neg__(self): # real signature unknown; restored from __doc__ 118 """ x.__neg__() <==> -x """ 119 pass 120 121 @staticmethod # known case of __new__ 122 def __new__(S, *more): # real signature unknown; restored from __doc__ 123 """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ 124 pass 125 126 def __nonzero__(self): # real signature unknown; restored from __doc__ 127 """ x.__nonzero__() <==> x != 0 """ 128 pass 129 130 def __oct__(self): # real signature unknown; restored from __doc__ 131 """ x.__oct__() <==> oct(x) """ 132 pass 133 134 def __or__(self, y): # real signature unknown; restored from __doc__ 135 """ x.__or__(y) <==> x|y """ 136 pass 137 138 def __pos__(self): # real signature unknown; restored from __doc__ 139 """ x.__pos__() <==> +x """ 140 pass 141 142 def __pow__(self, y, z=None): # real signature unknown; restored from __doc__ 143 """ x.__pow__(y[, z]) <==> pow(x, y[, z]) """ 144 pass 145 146 def __radd__(self, y): # real signature unknown; restored from __doc__ 147 """ x.__radd__(y) <==> y+x """ 148 pass 149 150 def __rand__(self, y): # real signature unknown; restored from __doc__ 151 """ x.__rand__(y) <==> y&x """ 152 pass 153 154 def __rdivmod__(self, y): # real signature unknown; restored from __doc__ 155 """ x.__rdivmod__(y) <==> divmod(y, x) """ 156 pass 157 158 def __rdiv__(self, y): # real signature unknown; restored from __doc__ 159 """ x.__rdiv__(y) <==> y/x """ 160 pass 161 162 def __repr__(self): # real signature unknown; restored from __doc__ 163 """ x.__repr__() <==> repr(x) """ 164 pass 165 166 def __rfloordiv__(self, y): # real signature unknown; restored from __doc__ 167 """ x.__rfloordiv__(y) <==> y//x """ 168 pass 169 170 def __rlshift__(self, y): # real signature unknown; restored from __doc__ 171 """ x.__rlshift__(y) <==> y<<x """ 172 pass 173 174 def __rmod__(self, y): # real signature unknown; restored from __doc__ 175 """ x.__rmod__(y) <==> y%x """ 176 pass 177 178 def __rmul__(self, y): # real signature unknown; restored from __doc__ 179 """ x.__rmul__(y) <==> y*x """ 180 pass 181 182 def __ror__(self, y): # real signature unknown; restored from __doc__ 183 """ x.__ror__(y) <==> y|x """ 184 pass 185 186 def __rpow__(self, x, z=None): # real signature unknown; restored from __doc__ 187 """ y.__rpow__(x[, z]) <==> pow(x, y[, z]) """ 188 pass 189 190 def __rrshift__(self, y): # real signature unknown; restored from __doc__ 191 """ x.__rrshift__(y) <==> y>>x """ 192 pass 193 194 def __rshift__(self, y): # real signature unknown; restored from __doc__ 195 """ x.__rshift__(y) <==> x>>y """ 196 pass 197 198 def __rsub__(self, y): # real signature unknown; restored from __doc__ 199 """ x.__rsub__(y) <==> y-x """ 200 pass 201 202 def __rtruediv__(self, y): # real signature unknown; restored from __doc__ 203 """ x.__rtruediv__(y) <==> y/x """ 204 pass 205 206 def __rxor__(self, y): # real signature unknown; restored from __doc__ 207 """ x.__rxor__(y) <==> y^x """ 208 pass 209 210 def __sizeof__(self, *args, **kwargs): # real signature unknown 211 """ Returns size in memory, in bytes """ 212 pass 213 214 def __str__(self): # real signature unknown; restored from __doc__ 215 """ x.__str__() <==> str(x) """ 216 pass 217 218 def __sub__(self, y): # real signature unknown; restored from __doc__ 219 """ x.__sub__(y) <==> x-y """ 220 pass 221 222 def __truediv__(self, y): # real signature unknown; restored from __doc__ 223 """ x.__truediv__(y) <==> x/y """ 224 pass 225 226 def __trunc__(self, *args, **kwargs): # real signature unknown 227 """ Truncating an Integral returns itself. """ 228 pass 229 230 def __xor__(self, y): # real signature unknown; restored from __doc__ 231 """ x.__xor__(y) <==> x^y """ 232 pass 233 234 denominator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 235 """the denominator of a rational number in lowest terms""" 236 237 imag = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 238 """the imaginary part of a complex number""" 239 240 numerator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 241 """the numerator of a rational number in lowest terms""" 242 243 real = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 244 """the real part of a complex number""" 245 246 long
3.浮点
如:3.123434
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 class float(object): 2 """ 3 float(x) -> floating point number 4 5 Convert a string or number to a floating point number, if possible. 6 """ 7 def as_integer_ratio(self): 8 """ 获取改值的最简比 """ 9 """ 10 float.as_integer_ratio() -> (int, int) 11 12 Return a pair of integers, whose ratio is exactly equal to the original 13 float and with a positive denominator. 14 Raise OverflowError on infinities and a ValueError on NaNs. 15 16 >>> (10.0).as_integer_ratio() 17 (10, 1) 18 >>> (0.0).as_integer_ratio() 19 (0, 1) 20 >>> (-.25).as_integer_ratio() 21 (-1, 4) 22 """ 23 pass 24 25 def conjugate(self, *args, **kwargs): # real signature unknown 26 """ Return self, the complex conjugate of any float. """ 27 pass 28 29 def fromhex(self, string): 30 """ 将十六进制字符串转换成浮点型 """ 31 """ 32 float.fromhex(string) -> float 33 34 Create a floating-point number from a hexadecimal string. 35 >>> float.fromhex('0x1.ffffp10') 36 2047.984375 37 >>> float.fromhex('-0x1p-1074') 38 -4.9406564584124654e-324 39 """ 40 return 0.0 41 42 def hex(self): 43 """ 返回当前值的 16 进制表示 """ 44 """ 45 float.hex() -> string 46 47 Return a hexadecimal representation of a floating-point number. 48 >>> (-0.1).hex() 49 '-0x1.999999999999ap-4' 50 >>> 3.14159.hex() 51 '0x1.921f9f01b866ep+1' 52 """ 53 return "" 54 55 def is_integer(self, *args, **kwargs): # real signature unknown 56 """ Return True if the float is an integer. """ 57 pass 58 59 def __abs__(self): 60 """ x.__abs__() <==> abs(x) """ 61 pass 62 63 def __add__(self, y): 64 """ x.__add__(y) <==> x+y """ 65 pass 66 67 def __coerce__(self, y): 68 """ x.__coerce__(y) <==> coerce(x, y) """ 69 pass 70 71 def __divmod__(self, y): 72 """ x.__divmod__(y) <==> divmod(x, y) """ 73 pass 74 75 def __div__(self, y): 76 """ x.__div__(y) <==> x/y """ 77 pass 78 79 def __eq__(self, y): 80 """ x.__eq__(y) <==> x==y """ 81 pass 82 83 def __float__(self): 84 """ x.__float__() <==> float(x) """ 85 pass 86 87 def __floordiv__(self, y): 88 """ x.__floordiv__(y) <==> x//y """ 89 pass 90 91 def __format__(self, format_spec): 92 """ 93 float.__format__(format_spec) -> string 94 95 Formats the float according to format_spec. 96 """ 97 return "" 98 99 def __getattribute__(self, name): 100 """ x.__getattribute__('name') <==> x.name """ 101 pass 102 103 def __getformat__(self, typestr): 104 """ 105 float.__getformat__(typestr) -> string 106 107 You probably don't want to use this function. It exists mainly to be 108 used in Python's test suite. 109 110 typestr must be 'double' or 'float'. This function returns whichever of 111 'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the 112 format of floating point numbers used by the C type named by typestr. 113 """ 114 return "" 115 116 def __getnewargs__(self, *args, **kwargs): # real signature unknown 117 pass 118 119 def __ge__(self, y): 120 """ x.__ge__(y) <==> x>=y """ 121 pass 122 123 def __gt__(self, y): 124 """ x.__gt__(y) <==> x>y """ 125 pass 126 127 def __hash__(self): 128 """ x.__hash__() <==> hash(x) """ 129 pass 130 131 def __init__(self, x): 132 pass 133 134 def __int__(self): 135 """ x.__int__() <==> int(x) """ 136 pass 137 138 def __le__(self, y): 139 """ x.__le__(y) <==> x<=y """ 140 pass 141 142 def __long__(self): 143 """ x.__long__() <==> long(x) """ 144 pass 145 146 def __lt__(self, y): 147 """ x.__lt__(y) <==> x<y """ 148 pass 149 150 def __mod__(self, y): 151 """ x.__mod__(y) <==> x%y """ 152 pass 153 154 def __mul__(self, y): 155 """ x.__mul__(y) <==> x*y """ 156 pass 157 158 def __neg__(self): 159 """ x.__neg__() <==> -x """ 160 pass 161 162 @staticmethod # known case of __new__ 163 def __new__(S, *more): 164 """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ 165 pass 166 167 def __ne__(self, y): 168 """ x.__ne__(y) <==> x!=y """ 169 pass 170 171 def __nonzero__(self): 172 """ x.__nonzero__() <==> x != 0 """ 173 pass 174 175 def __pos__(self): 176 """ x.__pos__() <==> +x """ 177 pass 178 179 def __pow__(self, y, z=None): 180 """ x.__pow__(y[, z]) <==> pow(x, y[, z]) """ 181 pass 182 183 def __radd__(self, y): 184 """ x.__radd__(y) <==> y+x """ 185 pass 186 187 def __rdivmod__(self, y): 188 """ x.__rdivmod__(y) <==> divmod(y, x) """ 189 pass 190 191 def __rdiv__(self, y): 192 """ x.__rdiv__(y) <==> y/x """ 193 pass 194 195 def __repr__(self): 196 """ x.__repr__() <==> repr(x) """ 197 pass 198 199 def __rfloordiv__(self, y): 200 """ x.__rfloordiv__(y) <==> y//x """ 201 pass 202 203 def __rmod__(self, y): 204 """ x.__rmod__(y) <==> y%x """ 205 pass 206 207 def __rmul__(self, y): 208 """ x.__rmul__(y) <==> y*x """ 209 pass 210 211 def __rpow__(self, x, z=None): 212 """ y.__rpow__(x[, z]) <==> pow(x, y[, z]) """ 213 pass 214 215 def __rsub__(self, y): 216 """ x.__rsub__(y) <==> y-x """ 217 pass 218 219 def __rtruediv__(self, y): 220 """ x.__rtruediv__(y) <==> y/x """ 221 pass 222 223 def __setformat__(self, typestr, fmt): 224 """ 225 float.__setformat__(typestr, fmt) -> None 226 227 You probably don't want to use this function. It exists mainly to be 228 used in Python's test suite. 229 230 typestr must be 'double' or 'float'. fmt must be one of 'unknown', 231 'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be 232 one of the latter two if it appears to match the underlying C reality. 233 234 Override the automatic determination of C-level floating point type. 235 This affects how floats are converted to and from binary strings. 236 """ 237 pass 238 239 def __str__(self): 240 """ x.__str__() <==> str(x) """ 241 pass 242 243 def __sub__(self, y): 244 """ x.__sub__(y) <==> x-y """ 245 pass 246 247 def __truediv__(self, y): 248 """ x.__truediv__(y) <==> x/y """ 249 pass 250 251 def __trunc__(self, *args, **kwargs): # real signature unknown 252 """ Return the Integral closest to x between 0 and x. """ 253 pass 254 255 imag = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 256 """the imaginary part of a complex number""" 257 258 real = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 259 """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
>>>