python中数字类型与处理工具

python中的数字类型工具

  python中为更高级的工作提供很多高级数字编程支持和对象,其中数字类型的完整工具包括:

  1.整数与浮点型,

  2.复数,

  3.固定精度十进制数,

  4.有理分数,

  5.集合,

  6.布尔类型

  7.无穷的整数精度

  8.各种数字内置函数及模块。

基本数字类型

  python中提供了两种基本类型:整数(正整数金额负整数)和浮点数(:带有小数部分的数字),其中python中我们可以使用多种进制的整数。并且整数可以用有无穷精度。

  整数的表现形式以十进制数字字符串写法出现,浮点数带一个小数点或者使用科学计数法e来表示。在python2版本中,整数还分为一般整数(32位)和长整数(无穷精度),长整数以l结尾。带了python3中整数就只有一种形式了,具有无尽精度。

  当然,在Python中整数还有二进制(0bxxxxxxxx),八进制(0oxxxxxxxx),和十六进制(0x xxxxxxxx)的形式出现。

  十进制数与其他进制的转换:

s=16
print(bin(s))
print(oct(s))
print(hex(s))

运行结果:
0b10000
0o20
0x10
print('{0:o},{1:x},{2:b}'.format(16,16,16))
print('%o,%x,%X'%(16,16,16))
运行结果:
20,10,10000
20,10,10

  其他进制转化为十进制:

a=int('0b10000',2)
b=int('0o20',8)
c=int('0x10',16)
print(a)
print(b)
print(c)
运行结果:
16
16
16
print(eval('16'))
print(eval('0b10000'))
print(eval('0o20'))
print(eval('0x10'))
运行结果:
16
16
16
16

python表达式操作符

  表达式是数学符号和操作符号写出来的,下表为python表达式操作符与程序:

操作符 描叙
yield 生成 器函数发送协议
lambda args:expression 生成匿名函数
x if y else z 三元表达式
x or y  逻辑或(存在短路算法)
x and y 逻辑与(存在短路算法)
not x 逻辑非
x in y , x not in y 成员关系
x is y ,x is not y 对象实体測试
x<y,x<=y,x>y,x>=y,x==y,x!=y 比較大小
x|y 位或,集合并集
x^y 位异或,集合对称差
x&y 位与,集合交集
x<<y,x>>y 左移或者右移y位
x+y,x-y 加减法、合并删除
x*y,x%y,x/y,x//y 乘,取余数,除,地板除
-x,+x 一元减法
~x 按位求补(取反)
x**y 幂运算
x[i] 索引,函数调用
x[i:j:k] 分片
x(...) 调用函数
x.attr 调用属性
(...) 元组,表达式,生成器
[...] 列表,列表解析
{...} 字典,集合,集合和字典解析

    :操作符在python2和python3中略有不同,python2中不等于用!=或》<>来表示,在python3中<>方法被取消,不等于就用!=来表示。

  x<y<z等同于x<y and y<z,

  在python2中可以使用混合类型,在python3中比较混合类型大小是会报错的,

python2
a = 1 > 'a' print a 运行结果: False
python3
a=1 > 'a' print(a) 运行结果: Traceback (most recent call last): File "C:/Users/jeff/PycharmProjects/python_file/practice/prac2.py", line 92, in <module> a=1 > 'a' TypeError: unorderable types: int() > str()

  上面的表格也是程序运行的优先级表格,自上而下,优先级越来越高,当然如果想要改变优先级,要是用括号来做。括号在python数字操作中经常会使用到,他不仅强制程序按照你想要的顺序运行,同时也增加了程序的可读性。

class int(object):
    """
    int(x=0) -> int or long
    int(x, base=10) -> int or long
    
    Convert a number or string to an integer, or return 0 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 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)
    4
    """
    def bit_length(self): 
        """ 返回表示该数字的时占用的最少位数 """
        """
        int.bit_length() -> int
        
        Number of bits necessary to represent self in binary.
        >>> bin(37)
        '0b100101'
        >>> (37).bit_length()
        6
        """
        return 0

    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=10): # known special case of int.__init__
        """ 构造方法,执行 x = 123 或 x = int(10) 时,自动调用,暂时忽略 """ 
        """
        int(x=0) -> int or long
        int(x, base=10) -> int or long
        
        Convert a number or string to an integer, or return 0 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 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)
        4
        # (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"""
int类的内置

混合类型

  这里指的是混合数字类型,比如整数和浮点数相加的结果是什么呢?

  其实在python中首先将备操作对象转换成其中最复杂的操作对象的类型,然后再进行相同类型的对象进行数学运算。

print(1+0.2)

运行结果:
1.2

  :除此之外,在python中还存在着运算符重载功能比如‘+’,除了做数字加法运算,在字符串拼接时也适用‘+’。

数字显示格式

  由于一些硬件限制,数字显示有时看起来会很奇怪,例如:

在命令行中操作
>>>num = 1 / 3.0
>>>num
0.333333333333333333331
在pycharm中print操作
num = 1/3.0
print(num)
运行结果:
0.3333333333333333
num = 1/3.0
print('{0:4.2f}'.format(num))#4是前面空格格数,2是保留小数位
运行结果:
0.33

  在命令行中显示的形式叫做默认的交互式回显,而print打印的叫做友好式回显,与reper和str的显示是一致的:

>>>num = 1/3.0
>>>repr(num)
0.333333333333333333331
>>>str(num)
0.3333333333333333

除法:传统除法,floor除法,真除法和截断除法

  除法是python2与python3之间非常重要的一个变化。

  一、除法操作符

  python有两种除法操作符‘x/y’与‘x//y’,其中‘/’在python2中是传统除法,即省略浮点数小数部分,然而显示整数,在python3中,除法就是真除法,即无论什么类型都会保留小数部分;‘//’也叫作floor除法,在python3中省略小数部分,剩下最小的能整除的整数部分,操作数如果是浮点数则结果显示浮点数,python2中整数截取整数,浮点数执行保留浮点数。

例:在python2中:

在python3中:

在python2中若是想要使用python3中的'/'则需要调用模块来完成,在python2中调用division模块:

 

  截断除法与floor除法一样都是取最接近整数向下取整,这使得在负数时也生效,即-2.5则为-3,而不是-2,想要得到真正的截取需要调用math模块:

  python还支持复数的计算:

还支持compliex(real,imag)来创建复数。

更多复数计算参考模块cmath的参考手册。

位操作

x=1
print(x<<2)
print(x|2)
print(x&2)
print(x^2)
运行结果:
4
3
0
3

  python3中使用bit_length查看二进制位数:

x=99
print(bin(x))
print(x.bit_length())
print(len(bin(x))-2)
运行结果:
0b1100011
7
7

内置数学工具

  math模块

import math
print(math.pi)
print(math.e)
print(math.sin(110))
print(math.sqrt(144))
print(pow(2,3))
print(abs(-50))
print(sum((1,2,3)))
print(max(1,2,3))
print(min(1,2,3))
运行结果:
3.141592653589793
2.718281828459045
-0.044242678085070965
12.0
8
50
6
3
1

  对于截取浮点数的操作有四种方式:

print(math.floor(2.577))
print(math.trunc(2.577))
print(round(2.577))
print(int(2.577))
运行结果:
2
2
3
2

  random模块

  获取随机数

import random
print(random.random())
print(random.randint(1,100))
运行结果:
0.9534845221467178
79

其他数字类型介绍

  除了常见的整型与浮点数,还有一些其他较为常见的数字类型。

  一、小数数字

  虽然学习python有一段时间了,但是确实没有太明白浮点数与小数的区别,其实小数在某种程度上就是浮点数,只不过他有固定的位数和小数点,在python中有专门的模块导入小数,from decimal import Decimal。

  浮点数缺乏精确性。

print(0.1+0.1+0.1-0.3)
输出结果:
5.551115123125783e-17

  我想看到这里的兄弟可能已经慌了,然后使用python解释器试了一下,果然结果就是5.551115123125783e-17虽然很接近0,但是不是0。所以说浮点型本质是缺乏精确性。要精确就需要调用from decimal import Decimal。

from decimal import Decimal
print(Decimal('0.1')+Decimal('0.10')+Decimal('0.10')-Decimal('0.30'))
运行结果:
0.00

  可以看出来小数相加也是自动升级为位数最多的。

  注:浮点数创建小数对象,由于浮点数本身可能就不精确所以转换会产生较多的位数。

from decimal import Decimal
print(Decimal.from_float(1.88))
print(Decimal.from_float(1.25))
输出结果:
1.87999999999999989341858963598497211933135986328125
1.25

  这里只是简单介绍一下小数,更多关于小数在以后看过Python标准库手册后再来总结。

  二、分数

  分数类型与小数极为相似,他们都是通过固定小数位数和指定舍入或截取策略控制精度。分数使用Fraction模块导入。

from fractions import Fraction
x=Fraction(1,3)
y=Fraction(2,3)
print(x+y)
输出结果:
1

  注:对于内存给定有限位数无法精确表示的值,浮点数的局限尤为明显。分数和小数都比浮点数更为准确。

  三、集合

      集合是无序元素组成,打印时顺序也是无序的,但是集合中没有重复的元素,所以我们常使用集合去重,尤其是在涉及数字和数据库的工作中。

      我们有两个集合a与b:

      a与b的交集为a.intersection(b)或者a & b。

      a与b的差集为a.difference(b)或者a-b。

      a与b的并集为a.union(b)或者a|b。

      反向差集与对称差集(并集减去交集)为a.symmetric_difference(b)或者a^b。

      合并为a.update(b),a.difference_update(b)求差集并赋值给a集合

      删除元素可用discard(元素)或者remove(元素),pop()是随机删除一个元素,add插入一个项目。

      注:set是可变数据类型,但是set里面的元素一定是不可变数据类型。

x={'a','c','b'}
y={'a','g','b'}
z={'a'}
print('a' in x)
print(x-y)
print(x|y)
print(x&y)
print(x^y)
print(z<y)
x={'a','c','b'}
y={'a','g','b'}
z={'a'}
print(x.intersection(y))
print(x.union(y))
x.add('s')
print(x)
print(x.pop())
x.update({'w','e','o'})
print(x)
print(x)
运行结果:
{'a', 'b'}
{'c', 'a', 'b', 'g'}
{'a', 'b', 'c', 's'}
a
{'o', 'c', 's', 'w', 'b', 'e'}
{'o', 'c', 's', 'w', 'b', 'e'}

  :在python中{}是空字典,如果想要定义空集合要用set()。

  集合要是添加列表等可变类型则会报错。

x={'a','c','b'}
l=[1,2,3]
x.add(l) print(x) 运行结果: Traceback (most recent call last): File
"C:/Users/jeff/PycharmProjects/python_file/practice/prac2.py", line 111, in <module> print(x.add(l)) TypeError: unhashable type: 'list'

  正确的添加序列方式为添加元组。

x={'a','c','b'}
l=(1,2,3)
x.add(l)
print(x)
运行结果:
{'c', 'b', 'a', (1, 2, 3)}

  定义不可操作的集合使用frozenset定义集合。

  字典解析:

  与列表解析相类似,集合也是可迭代对象,所以可以使用for循环遍历。

x={1,2,3}
print({i ** 2 for i in x})
运行结果:
{1, 9, 4}

  四、布尔值

  python的一个数据类型,有两个值Ture 与 False。

print(type(True))
print(True == 1)
print(True is 1)
print(True + 1)
运行结果:
<class 'bool'>
True
False
2

 

  集合和bool值,还是比较常见的类型,在基础学习里也有涉及,在这里就不多写了。

  python中的数字在程序编写时广泛使用,今后还会更深层次的学习python的扩展库。

posted @ 2017-08-01 21:17  JeffD  阅读(2525)  评论(0编辑  收藏  举报