1.內置函式分類
思維導圖: https://www.processon.com/view/link/5dcabc48e4b0bd68d813b24f
2.基礎資料型別-和數字相關的函式(14)
資料型別-bool
bool()函式用于將給定引數轉換為布爾型別,如果沒有引數,回傳 False
bool 是 int 的子類
print(bool(0)) # False # bool 是 int 子類 issubclass(bool, int) # True
資料型別-int
int()函式將給定的資料轉換成int值,如果不給值則回傳0
# 不傳入引數時,得到結果0 int() # 0 # 可以指定轉換16進制 int('f', 16) # 15 # 指定轉換2進制 int('11', 2) # 3 # 指定轉換8進制 int('11', 8) # 9
資料型別-float
float()函式用于將整數和字串轉換成浮點數
float(1) # 1.0 float(112) # 112.0 float(-123.6) # -123.6 # 字串 float('123') # 123.0
資料型別-complex
complex()函式用于創建一個值為real+imag*j的復數,或者轉化一個字串或數為復數
complex(1, 2) # (1 + 2j) complex(1) # 數字(1 + 0j) # 如果第一個引數為字串,則不需要指定第二個引數 complex("1") # 當做字串處理(1 + 0j) # 注意: 這個地方在"+"號兩邊不能有空格,也就是不能寫成"1 + 2j",應該是"1+2j",否則會報錯 complex("1+2j") # (1 + 2j)
進制轉換-bin
bin()十進制轉二進制
print(bin(3)) # 0b11
進制轉換-oct
oct()函式將一個整數轉換成8進制字串
print(oct(10)) # 0o12
進制轉換-hex
hex()函式用于將10進制整數轉換成16進制,以字串形式表示
print(hex(10)) # 0xa print(type(hex(12))) # <class 'str'>
數學運算-abs
abs()函式回傳數字的絕對值
print(abs(-1)) # 1
數學運算-divmod
divmod()函式把除數和余數運算結果結合起來,回傳一個包含商和余數的元組
print(divmod(10, 3)) # (3, 1)
數學運算-round
round()函式回傳浮點數x的四舍五入值
print(round(3.5)) # 4 print(round(3.1415, 2)) # 3.14
數學運算-pow
pow(a, b)函式求a的b次冪,如果有三個引數則求完次冪后對第三個數取余
pow(2, 10) # 1024 # 2的10次方除以100取余數 pow(2, 10, 100) # 24 # pow x**y%z print(pow(2, 3)) # 2的3次方 ==>8 print(pow(2, 3, 7)) # 2**3%7 ==>1
數學運算-sum
sum()函式對序列進行求和計算
t1 = [1, 2, 3, 4] print(sum(t1)) # 10
數學運算-min
min()函式處理的是可迭代物件相當于for回圈取出每個元素進行比較,然后取最小值,不同型別不能進行比較
元素與元素比較是從元素的第一個位置開始,第一個位置分出大小,后面位置不需比較,實際比較的是Unicode值
list1 = [1, 10, -50, 100] print(min(list1)) # -50
數學運算-max
max()函式處理的是可迭代物件相當于for回圈取出每個元素進行比較,然后取最大值,不同型別不能進行比較
元素與元素比較是從元素的第一個位置開始,第一個位置分出大小,后面位置不需比較,實際比較的是Unicode值
list1 = [1, 10, -50, 100] print(max(list1)) # 100 # 串列嵌套取字典中年齡最大的key和value people = [ {"name": "zhangsan", "age": 18}, {"name": "lisi", "age": 15}, {"name": "wangwu", "age": 22}, {"name": "dingliu", "age": 30} ] print(max(people, key=lambda dic: dic["age"])) # {'name': 'dingliu', 'age': 30}
3.基礎資料型別-和資料結構相關的函式(24)
序列-字串(str)
str()函式將物件轉化為字串
str(10) # '10' str(list(x for x in range(5))) # '[0, 1, 2, 3, 4]'
序列-字串(format)
format()與具體資料相關,用于計算各種小數,精算等
# 字串 print(format('test', '<20')) # 左對齊 print(format('test', '>20')) # 右對齊 print(format('test', '^20')) # 居中 # 數值 print(format(3, 'b')) # 二進制 print(format(97, 'c')) # 轉換成unicode字符 print(format(11, 'd')) # 十進制 print(format(11, 'o')) # 八進制 print(format(11, 'x')) # 十六進制(小寫字母) print(format(11, 'X')) # 十六進制(大寫字母) print(format(11, 'n')) # 和d一樣 print(format(11)) # 和d一樣 # 浮點數 print(format(123456789, 'e')) # 科學計數法默認保6位小數 print(format(123456789, '0.2e')) # 科學計數法保留2位小數(小寫) print(format(123456789, '0.2E')) # 科學計數法保留2位小數(大寫) print(format(1.23456789, 'f')) # 小數點計數法保留6位小數 print(format(1.23456789, '0.2f')) # 小數點計數法保留2位小數 print(format(1.23456789, '0.10f')) # 小數點計數法保留10位小數 print(format(1.23456789e+10000, 'F')) # 小數點計數法,很大的時候輸出無窮大: INF
序列-字串(ord)
ord()函式以一個字符長度為1的字串作為引數,回傳對應的 ASCII 數值,或者 Unicode 數值
print(ord("a"), ord("A")) # 97 65 # 回傳對應的Unicode值 ord('唐') # 21776
序列-字串(chr)
chr()函式用一個范圍在range(256)內也就是0~255的整數作引數,回傳一個對應ASCII字符
# 十六進制 print (chr(0x30), chr(0x31), chr(0x61)) # 0 1 a # 十進制 print (chr(48), chr(49), chr(97)) # 0 1 a
序列-字串(ascii)
ascii()函式是ascii碼中的回傳該值 不是就回傳Unicode或物件的記憶體地址
print(ascii('a')) # 'a' print(ascii('好')) # '\u597d'
序列-字串(repr)
repr()函式回傳一個物件的str形式供解釋器讀取
# repr 就是原封不動的輸出, 引號和轉義字符都不起作用 print(repr('大家好,\n \t我叫coco')) # '大家好,\n \t我叫coco' print('大家好我叫coco') # 大家好我叫coco # %r 原封不動的寫出來 name = 'cat' print('我叫%r' % name) # 我叫'cat'
序列-位元組(bytes)
bytes()函式可以將引數轉換成位元組,encoding指定編碼,decode指定解碼
name = "你好" print(bytes(name, encoding='gbk')) # b'\xc4\xe3\xba\xc3' print(bytes(name, encoding='gbk').decode('gbk')) # 你好
序列-位元組(bytearray)
bytearray()函式回傳一個新位元組陣列,這個陣列里的元素是可變的,并且每個元素的值得范圍是'[0,256)'
ret = bytearray('coco',encoding='utf-8') print(ret[0]) # 99 print(ret) # bytearray(b'coco') print(bytearray([1,2,3])) # bytearray(b'\x01\x02\x03')
序列-位元組(memoryview)
memoryview()函式查看bytes在記憶體中的情況
s = memoryview("coco".encode("utf-8")) # 查看bytes位元組在記憶體中的情況 print(s) # <memory at 0x00000000048DCAC8> v = memoryview(bytearray("abcefg", 'utf-8')) print(v[1]) # 98 print(v[-1]) # 103 print(v[1:4]) # <memory at 0x10f543a08> print(v[1:4].tobytes()) # b'bce'
序列-串列(list)
list()函式將一個可迭代物件轉換成串列
list({'name': 'coco', 'age': 18}) # ['name', 'age']
list('abcdee') # ['a', 'b', 'c', 'd', 'e', 'e']
序列-元祖(tuple)
tuple()函式將一個可迭代物件轉換成元組
# 針對字典會回傳字典的key組成的tuple tuple({1:2,3:4}) # (1, 3) tuple([1,2,3,4]) # (1, 2, 3, 4)
序列-翻轉(reversed)
reversed()函式將一個序列翻轉,回傳翻轉序列的迭代器
list(reversed(range(10))) # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
序列-自定義切片(slice)
slice()函式自定義切片
myslice = slice(5) # 設定截取5個元素的切片 myslice # slice(None, 5, None) arr = range(10) arr # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # 截取5個元素 arr[myslice] # [0, 1, 2, 3, 4]
資料集合-字典(dict)
dict()函式創建一個字典
# 創建空字典 dict() # {} # 傳入關鍵字 dict(a='a', b='b', t='t') # {'a': 'a', 'b': 'b', 't': 't'} # 映射函式方式來構造字典 dict(zip(['one', 'two', 'three'], [1, 2, 3])) # {'three': 3, 'two': 2, 'one': 1} # 可迭代物件方式來構造字典 dict([('one', 1), ('two', 2), ('three', 3)]) # {'three': 3, 'two': 2, 'one': 1}
資料集合-集合(set)
set()函式創建一個集合
x = set('runoob') y = set('google') x, y # 重復的被洗掉 ({'b', 'n', 'o', 'r', 'u'}, {'e', 'g', 'l', 'o'}) x & y # 交集 {'o'} x | y # 并集 {'b', 'e', 'g', 'l', 'n', 'o', 'r', 'u'} x - y # 差集 {'b', 'n', 'r', 'u'}
資料集合-固定集合(frozenset)
frozenset()函式回傳一個凍結的集合,凍結后集合不能再添加或洗掉任何元素
a = frozenset(range(10)) # 生成一個新的不可變集合 a # frozenset([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) b = frozenset('runoob') # 創建不可變集合 b # frozenset(['b', 'r', 'u', 'o', 'n'])
其他-len
len()函式回傳物件(字符,串列,元組等)長度或專案個數
str = "runoob" # 字串長度 len(str) # 6 l = [1,2,3,4,5] # 串列元素個數 len(l) # 5
其他-sorted
sorted()函式對所有可迭代的物件進行排序操作
list1 = [1, 3, 5, 2, 9] print(sorted(list1)) # 排序本質就是比較Unicode值的大小,不同型別無法排序 # sorted串列嵌套排序 people1 = [ {"name": "zhangsan", "age": 18}, {"name": "lisi", "age": 15}, {"name": "wangwu", "age": 22}, {"name": "dingliu", "age": 30} ] print(sorted(people1, key=lambda dic: dic["age"])) # 按age從小到大排序
其他-enumerate
enumerate()函式用于將一個可遍歷的資料物件(如串列,元組或字串)
# 組合為一個索引序列同時列出資料和資料下標,一般用在 for 回圈遍歷當中 lst = ["coco", "angels", "cat"] # enumerate(lst, 1) 可以指定開始下標 # for index, el in enumerate(lst, 1): for index, el in enumerate(lst): print(str(index)+"==>"+el, end=' ') # 0==>coco 1==>angels 2==>cat
其他-all
all()函式將可迭代物件中的所有元素做布爾運算,1個為 False 全都為 False
# all 如果可迭代物件為空,則回傳True all([]) # True print(all([1, "ss", ()])) # False
其他-any
any()函式判斷給定的可迭代物件中有一個是 True, 結果就是 True, 全部為 False,則回傳 False
any([0, 1, 2]) # True any([None, (), {}]) # False
其他-zip
zip()函式用于將可迭代的物件作為引數,將物件中對應的元素打包成一個個元組,然后回傳由這些元組組成的串列,
如果各個迭代器的元素個數不一致,則回傳串列長度與最短的物件相同
l1 = [1,2,3,] l2 = ['a','b','c',5] l3 = ('*','**',(1,2,3)) for i in zip(l1,l2,l3): print(i, end= ' ') # (1, 'a', '*') (2, 'b', '**') (3, 'c', (1, 2, 3))
其他-filter
filter()函式用于過濾序列,過濾掉不符合條件的元素,回傳由符合條件元素的迭代器
def is_odd(n): return n % 2 == 1 newlist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) print(list(newlist)) # [1, 3, 5, 7, 9]
其他-map
map()函式會根據提供的函式對指定序列做映射
def square(x): """計算平方數""" return x ** 2 # 計算串列各個元素的平方 list(map(square, [1,2,3,4,5])) # [1, 4, 9, 16, 25] # 使用 lambda 匿名函式 list(map(lambda x: x ** 2, [1, 2, 3, 4, 5])) # [1, 4, 9, 16, 25] # 提供了兩個串列,對相同位置的串列資料進行相加 list(map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])) # [3, 7, 11, 15, 19]
4.作用域相關的函式(2)
全域變數-globals
globals()函式查看全域變數,包含系統提供的全域變數
a='coco' print(globals()) # globals 函式回傳一個全域變數的字典,包括所有匯入的變數 """ {'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__doc__': None, 'a': 'coco', '__package__': None} """
區域變數-locals
locals()函式查看當前級別的區域變數,包含當前級別系統提供的區域變數
def runoob(arg): # 兩個區域變數: arg,z z = 1 print (locals()) runoob(4) # {'z': 1, 'arg': 4}回傳一個'變數名:系結值'對應的字典
5.反射相關的函式(4)
判斷-hasattr
hasattr()函式用于判斷物件是否包含對應的屬性
class Coordinate: x = 10 y = -5 z = 0 point1 = Coordinate() print(hasattr(point1, 'x')) # True print(hasattr(point1, 'y')) # True print(hasattr(point1, 'z')) # True print(hasattr(point1, 'no')) # False沒有該屬性
獲取-getattr
getattr()函式用于回傳一個物件屬性值
class A: bar = 1 a = A() getattr(a, 'bar') # 獲取屬性 bar 值1 getattr(a, 'bar2') # 屬性 bar2 不存在,觸發例外 '''例外提示 AttributeError Traceback (most recent call last) <ipython-input-1-51bf4194ae4f> in <module> 5 a = A() 6 getattr(a, 'bar') # 獲取屬性 bar 值1 ----> 7 getattr(a, 'bar2') AttributeError: 'A' object has no attribute 'bar2' ''' getattr(a, 'bar2', 3) # 屬性 bar2 不存在,但設定了默認值3
設定-setattr
setattr()函式用于設定屬性值,該屬性不一定是存在的,如果屬性不存在會創建一個新的物件屬性,并對屬性賦值
class A(): name = "runoob" a = A() setattr(a, "age", 28) print(a.age) # 28
洗掉-delattr
delattr()函式用于洗掉屬性
class Coordinate: x = 10 y = -5 z = 0 point1 = Coordinate() print('x = ',point1.x) # ('x = ', 10) print('y = ',point1.y) # ('y = ', -5) print('z = ',point1.z) # ('z = ', 0) delattr(Coordinate, 'z') print('--洗掉 z 屬性后--') # --洗掉 z 屬性后-- print('x = ',point1.x) # ('x = ', 10) print('y = ',point1.y) # ('y = ', -5) # 會觸發錯誤 print('z = ',point1.z) # AttributeError: Coordinate instance has no attribute 'z'
6.迭代器生成器相關的函式(3)
range
range()生成器函式可創建一個整數迭代器
list(x for x in range(10) if x % 2 == 0) # [0, 2, 4, 6, 8]
next
next()函式讓迭代器向下執行一次,內部實際使用了__next__()方法回傳迭代器的下一個專案
# 首先獲得Iterator物件 it = iter([1, 2, 3, 4, 5]) # 其次回圈拿值 while True: try: # 獲得下一個值 x = next(it) print(x, end=' ') # 1 2 3 4 5 except StopIteration: # 遇到StopIteration就退出回圈 break
iter
iter()函式獲取迭代器,內部實際使用的是__iter__()方法來獲取迭代器
lst = [1, 2, 3] for i in iter(lst): print(i, end=' ') # 1 2 3
7.面向物件相關的函式(9)
isinstance
isinstance(obj,cls)函式檢查obj是否是類 cls 的物件
isinstance() 與 type() 區別:
type()函式不會認為子類是一種父型別別,即不考慮繼承關系
isinstance()函式會認為子類是一種父型別別,即考慮繼承關系
print(isinstance(123, int)) # True
class A: pass class B(A): pass isinstance(A(), A) # True type(A()) == A # True isinstance(B(), A) # True type(B()) == A # False
issubclass
issubclass(sub, super)函式檢查sub類是否是 super 類的派生類
class A: pass class B(A): pass print(issubclass(B,A)) # 回傳 True
object
object()函式回傳一個沒有特征的新物件,object是所有類的基類,它具有所有Python類實體的通用方法,object函式不接受任何實參
由于 object 沒有 __dict__字典 因此無法將任何屬性賦給 object 的實體
class A: pass a = A() print("實體a的__dict__字典: %s" % a.__dict__) obj = object() print(obj.__dict__) # 報錯,object()實體化的物件沒有__dict__屬性 """執行結果 實體a的__dict__字典: {} --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-22-e65e48d77a62> in <module> 7 8 obj = object() ----> 9 print(obj.__dict__) # 報錯,object()實體化的物件沒有__dict__屬性 AttributeError: 'object' object has no attribute '__dict__' """
staticmethod
staticmethod()函式修飾對應的方法變成靜態方法,被裝飾的方法不需要任何引數
class C: @staticmethod def run(): print('靜態方法運行了') C.run() # 靜態方法無需實體化 cobj = C() cobj.run() # 也可以實體化后呼叫
classmethod
classmethod()函式修飾對應的方法變成類方法,不需要實體化,不需要 self 引數,但第一個引數需要是表示自身類的 cls 引數
classmethod()函式修飾對應的方法可以來呼叫類的屬性,類的方法
class A: bar = 1 def func1(self): self.b = 3 print ('foo') @classmethod def func2(cls): print ('func2') # func2 print (cls.bar) # 1 cls().func1() # foo A.func2() # 不需要實體化便可直接用類名呼叫
property
property()函式修飾對應的方法變成靜態屬性
class A: # property將類中的方法偽裝成類屬性來呼叫 @property def test(self): print('test') a = A() a.test # test
super
super()函式是用于呼叫父類(超類)的一個方法
super()函式常用來解決多重繼承問題的,直接用類名呼叫父類方法在使用單繼承的時候沒問題,但是如果使用多繼承,
會涉及到查找順序(MRO),重復呼叫(鉆石繼承)等種種問題,MRO就是類的方法決議順序表,即繼承父類方法的順序表
class A: def add(self, x): y = x+1 print(y) class B(A): def add(self, x): super().add(x) b = B() b.add(2) # 3
vars
vars()函式以字典的形式查看物件的內置方法,不加引數查看當前級別的區域變數,包含當前級別系統提供的區域變數
msg = "xcafsfa" print(locals()) # {'msg': 'xcafsfa'} print(vars()) # {'msg': 'xcafsfa'} print(vars(int)) # {'__repr__': <slot wrapper '__repr__' of 'int' objects>, ...}
type
type()函式如果你只有第一個引數則回傳物件的型別,三個引數時回傳新的型別物件
# 一個引數 type(1) # <type 'int'> type('runoob') # <type 'str'> type([2]) # <type 'list'> type({0:'zero'}) # <type 'dict'> x = 1 # 判斷型別是否相等 type( x ) == int # True # 三個引數 class X: a = 1 X = type('X', (object,), dict(a=1)) # 產生一個新的型別物件 X X # <class '__main__.X'>
8.其他函式(13)
字串型別代碼的執行-eval
eval()函式用來執行一個字串運算式,把字串中的資料結構提取出來,并回傳運算式的值
# eval把字串中的資料結構提取出來 str1 = "{'name':'coco'}" d1 = eval(str1) print(type(d1)) # <class 'dict'> # eval把字串中的運算式作計算 str2 = "(1+2)*3-3" print(eval(str2)) # 6
字串型別代碼的執行-exec
exec()函式把字串以代碼的方式執行
exec(""" for i in range(10):print(i) """) exec(""" def func(): print("我是coco") func() """)
字串型別代碼的執行-compile
compile()函式將字串型別的代碼變異,代碼物件能夠通過 exec() 陳述句來執行或者 eval() 進行求值
有回傳值的字串形式的代碼用 eval(); 沒有回傳值的字串形式的代碼用 exec()
compile()函式引數說明
引數一: resource 要執行的代碼,動態代碼片段
引數二: 檔案名,代碼存放的檔案名,當傳入了第一個引數的時候,這個引數給空就可以了
引數三: 模式,取值有3個:
exec: 一般放一些流程陳述句的時候
eval: resource只存放一個求值運算式
single: resource存放的代碼有互動的時候mode應為single
code1 = "for i in range(10): print(i, end=' ')" c1 = compile(code1, "", mode="exec") # compile并不會執行代碼,只是編譯 # 執行編譯后的代碼 exec(c1) # 0 1 2 3 4 5 6 7 8 9
code2 = "1+2+3" c2 = compile(code2, "", mode="eval") a = eval(c2) print(a) # 6
code3 = "name = input('請輸入你的名字:')" c3 = compile(code3, "", mode="single") exec(c3) print(name)
輸入-input
input()函式接受一個標準輸入資料,回傳為 str 型別
print(input('請輸入:')) print(input('請輸入:') or "-1") # 用戶直接回車回傳字串 '-1'
輸出-print
print()函式列印輸出,end=設定以什么結尾,sep=設定間隔符
print("https:/","www.cnblogs.com","tangxuecheng",sep="/") # https://www.cnblogs.com/tangxuecheng
記憶體相關-hash
hash()演算法函式,可hash的資料型別即不可變資料型別,不可hash的資料型別即可變資料型別
hash特性1: hash無論傳入的引數長短,hash得出的值長度固定
hash特性2: 不能根據hash結果值推算傳入的具體資料
hash('test') # -7108862475672989075 hash(1) # 1 hash(str([1,2,3])) # -4688137874008436223 hash(str(sorted({'1':1}))) # -4466824049926549424
記憶體相關-id
id()函式獲取到物件的記憶體地址
name = 'coco' id(name) # 78357592
檔案操作相關-open
open()函式用于口打開一個檔案,回傳一個檔案句柄file物件
f = open('a.xtx', 'w') f.write('hello') f.close()
模塊相關-__import__
__import__()函式用于動態加載類和函式,如果一個模塊經常變化就可以使用 __import__() 來動態載入
import os print ('在 a.py 檔案中 %s' % id(os)) # 在 a.py 檔案中 30713320 import sys __import__('a') # 匯入 a.py 模塊
幫助-help
help()函式查看幫助
print(help(hash)) # 查看方法的具體解釋
呼叫相關-callable
callable(obj)函式用于檢查一個物件是否可呼叫,如果回傳True,obj有可能呼叫失敗,如果回傳False那呼叫絕對不會成功
class A: def method(self): return 0 callable(A) # 類回傳True a = A() callable(a) # 沒有實作__call__回傳False class B: def __call__(self): return 0 callable(B) # True b = B() callable(b) # 實作__call__回傳 True
查看內置屬性-dir
dir()函式不帶引數時,回傳當前范圍內的變數,方法和定義的型別串列,帶引數時回傳引數的屬性和方法串列
如果引數包含方法__dir__(),該方法將被呼叫,如果引數不包含__dir__(),該方法將最大限度地收集引數資訊
print(dir(all)) # ['__call__', '__class__', '__delattr__'...]
內建除錯-breakpoint
breakpoint()函式在未設定 PYTHONBREAKPOINT 環境變數的情況下,會中斷當前程式并進入 pdb 除錯器
import time print(time.ctime()) breakpoint() print('Good morning') """執行結果 Sun Jul 26 19:58:37 2020 --Return-- > <ipython-input-26-ba7b402eb64c>(4)<module>()->None -> breakpoint() (Pdb) """
# 原理剖析 # In builtins. def breakpoint(*args, **kws): import sys missing = object() hook = getattr(sys, 'breakpointhook', missing) if hook is missing: raise RuntimeError('lost sys.breakpointhook') return hook(*args, **kws) # In sys. def breakpointhook(*args, **kws): import importlib, os, warnings hookname = os.getenv('PYTHONBREAKPOINT') if hookname is None or len(hookname) == 0: hookname = 'pdb.set_trace' elif hookname == '0': return None modname, dot, funcname = hookname.rpartition('.') if dot == '': modname = 'builtins' try: module = importlib.import_module(modname) hook = getattr(module, funcname) except: warnings.warn( 'Ignoring unimportable $PYTHONBREAKPOINT: {}'.format( hookname), RuntimeWarning) return hook(*args, **kws) __breakpointhook__ = breakpointhook
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/59863.html
標籤:Python
下一篇:數字型別
