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的擴展庫。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM