1. 內(nèi)置函數(shù)六大類(lèi)
圖片:
鏈接:
2. 作用域相關(guān)
locals()
返回本地作用域中的所有名字
globals()
返回全局作用域中的所有名字
3. 迭代器/生成器相關(guān)
3.1 next()
next(迭代器) # 效果等同于 迭代器.__next__()
范例:
def next(迭代器):
迭代器.__next__()
3.2 iter()
迭代器 = iter(可迭代的) # 相當(dāng)于:迭代器 = 可迭代的.__iter__()
3.3 range()
range是可迭代的,但不是迭代器
range(10)
range(1,11)
range(1,11,2)
4. 其他
4.1 查看內(nèi)置屬性:dir()
查看一個(gè)變量擁有的方法
范例:
print(dir([]))
print(dir(1))
執(zhí)行結(jié)果:
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
4.2 幫助:help()
help() 函數(shù)用于查看函數(shù)或模塊用途的詳細(xì)說(shuō)明。
范例:
help(str)
執(zhí)行結(jié)果:
Help on class str in module builtins:
.
.
.
| must be a string, whose characters will be mapped to None in the result.
4.3 調(diào)用相關(guān):callable()
callable() 函數(shù)用于檢查一個(gè)對(duì)象是否是可調(diào)用的烹玉。(凡是后面加括號(hào)調(diào)用的都是True)
范例:
print(callable(print))
a = 1
print(callable(a))
print(callable(globals))
def func():pass
print(callable(func))
執(zhí)行結(jié)果:
True
False
True
True
4.4 模塊相關(guān):import
import的作用是導(dǎo)入模塊
范例:__import__
(了解即可)
t = __import__("time")
print(t.time())
執(zhí)行結(jié)果:
1547557124.231164
4.4.1 小結(jié)
某個(gè)方法屬于某個(gè)數(shù)據(jù)類(lèi)型的變量芝硬,就用.調(diào)用
如果某個(gè)方法不依賴(lài)于任何數(shù)據(jù)類(lèi)型遍蟋,就直接調(diào)用 —— 內(nèi)置函數(shù) 和 自定義函數(shù)
4.5 文件操作相關(guān):open()
范例:
f = open('1.復(fù)習(xí).py')
print(f.writable()) # 文件能不能寫(xiě)
print(f.readable()) # 文件能不能讀
執(zhí)行結(jié)果:
False
True
4.6 內(nèi)存相關(guān):id()與hash()
4.6.1 id()
id() 函數(shù)用于獲取對(duì)象的內(nèi)存地址痢法。
4.6.2 hash()
hash() 用于獲取取一個(gè)對(duì)象(字符串或者數(shù)值等)的哈希值峦筒。
對(duì)于相同可hash數(shù)據(jù)的hash值在一次程序的執(zhí)行過(guò)程中總是不變的
范例:hash()
print(hash(12345))
print(hash('hsgda不想你走,nklgkds'))
print(hash(('1','aaa')))
執(zhí)行結(jié)果:
12345
9093381866357115561
-2751277933709817804
4.7 輸入輸出:input與print
4.7.1 input()
范例:
ret = input('提示 : ')
print(ret)
執(zhí)行結(jié)果:
提示 : aaa
aaa
4.7.2 print()
范例1:
print('我們的祖國(guó)是花園\n')
print('我們的祖國(guó)是花園\n')
print('我們的祖國(guó)是花園\n',end='') #指定輸出的結(jié)束符
print('我們的祖國(guó)是花園\n',end='')
執(zhí)行結(jié)果:
我們的祖國(guó)是花園
我們的祖國(guó)是花園
我們的祖國(guó)是花園
我們的祖國(guó)是花園
范例2:
print(1,2,3,4,5)
print(1,2,3,4,5,sep='|') #指定輸出多個(gè)值之間的分隔符
執(zhí)行結(jié)果:
1 2 3 4 5
1|2|3|4|5
范例3:
f = open('file','w')
print('aaaa',file=f) # 直接把“aaaa”輸出到文件file內(nèi)了
f.close()
范例4:
打印進(jìn)度條
如要研究卦碾,網(wǎng)上查找模塊progress Bar
import time
for i in range(0,101,2):
time.sleep(0.1)
char_num = i//2
per_str = '\r%s%% : %s\n' % (i, '*' * char_num) \
if i == 100 else '\r%s%% : %s' % (i,'*'*char_num) # \r 意為回到行首
print(per_str,end='', flush=True)
執(zhí)行結(jié)果:
100% : **************************************************
4.8 字符串類(lèi)型代碼的執(zhí)行:eval與exec與compile
4.8.1 exec與eval
exec和eval都可以執(zhí)行 字符串類(lèi)型的代碼
eval有返回值 —— 有結(jié)果的簡(jiǎn)單計(jì)算
exec沒(méi)有返回值 —— 簡(jiǎn)單流程控制
eval只能用在你明確知道你要執(zhí)行的代碼是什么(慎用
)
范例1:
exec與eval
exec('print(123)')
eval('print(123)')
print(eval('1+2+3+4')) # 有返回值
print(exec('1+2+3+4')) #沒(méi)有返回值
執(zhí)行結(jié)果:
123
123
10
None
范例2:
exec
code = '''for i in range(10):
print(i*'*')
'''
exec(code)
執(zhí)行結(jié)果:
*
**
***
****
*****
******
*******
********
*********
4.8.2 compile
compile 將字符串類(lèi)型的代碼編譯。代碼對(duì)象能夠通過(guò)exec語(yǔ)句來(lái)執(zhí)行或者eval()進(jìn)行求值起宽。
參數(shù)說(shuō)明:
參數(shù)source:字符串或者AST(Abstract Syntax Trees)對(duì)象洲胖。即需要?jiǎng)討B(tài)執(zhí)行的代碼段。
參數(shù) filename:代碼文件名稱(chēng)坯沪,如果不是從文件讀取代碼則傳遞一些可辨認(rèn)的值绿映。當(dāng)傳入了source參數(shù)時(shí),filename參數(shù)傳入空字符即可腐晾。
參數(shù)model:指定編譯代碼的種類(lèi)叉弦,可以指定為 ‘exec’,’eval’,’single’。當(dāng)source中包含流程語(yǔ)句時(shí)藻糖,model應(yīng)指定為‘exec’淹冰;當(dāng)source中只包含一個(gè)簡(jiǎn)單的求值表達(dá)式,model應(yīng)指定為‘eval’巨柒;當(dāng)source中包含了交互式命令語(yǔ)句樱拴,model應(yīng)指定為'single'
范例1:
用compile編譯成exec模式
code1 = 'for i in range(0,10): print (i)'
compile1 = compile(code1,'','exec')
exec(compile1)
執(zhí)行結(jié)果:
0
1
2
3
4
5
6
7
8
9
范例2:
code2 = '1 + 2 + 3 + 4'
compile2 = compile(code2,'','eval')
print(eval(compile2))
執(zhí)行結(jié)果:
10
范例3:
single交互類(lèi)
code3 = 'name = input("please input your name:")'
compile3 = compile(code3,'','single')
exec(compile3) #執(zhí)行時(shí)顯示交互命令,提示輸入
print(name)
執(zhí)行結(jié)果:
please input your name:abc
abc
5. 基礎(chǔ)數(shù)據(jù)類(lèi)型相關(guān)
5.1 和數(shù)字相關(guān)
5.1.1 complex
# 復(fù)數(shù) —— complex
# 實(shí)數(shù) : 有理數(shù)
# 無(wú)理數(shù)
# 虛數(shù) :虛無(wú)縹緲的數(shù)
# 5 + 12j === 復(fù)合的數(shù) === 復(fù)數(shù)
# 6 + 15j
# 浮點(diǎn)數(shù)(有限循環(huán)小數(shù)洋满,無(wú)限循環(huán)小數(shù)) != 小數(shù) :有限循環(huán)小數(shù)晶乔,無(wú)限循環(huán)小數(shù),無(wú)限不循環(huán)小數(shù)
# 浮點(diǎn)數(shù)
#354.123 = 3.54123*10**2 = 35.4123 * 10
# f = 1.781326913750135970
# print(f)
5.1.2 進(jìn)制轉(zhuǎn)換 bin和oct和hex
bin(二進(jìn)制) & oct(八進(jìn)制) & hex(十六進(jìn)制)
print(bin(10))
print(oct(10))
print(hex(10))
執(zhí)行結(jié)果:
0b1010
0o12
0xa
5.1.3 數(shù)學(xué)運(yùn)算
- abs
abs() 函數(shù)返回?cái)?shù)字的絕對(duì)值牺勾。
print(abs(-5))
print(abs(5))
執(zhí)行結(jié)果:
5
5
2)divmod
divmod() 函數(shù)把除數(shù)和余數(shù)運(yùn)算結(jié)果結(jié)合起來(lái)正罢,返回一個(gè)包含商和余數(shù)的元組(a // b, a % b)。
print(divmod(7,2)) # div除法 mod取余
print(divmod(9,5)) # 除余
執(zhí)行結(jié)果:
(3, 1)
(1, 4)
3)round
round() 方法返回浮點(diǎn)數(shù)x的四舍五入值驻民。
print(round(3.14159,3))
執(zhí)行結(jié)果:
3.142
4)pow
pow() 方法返回 xy(x的y次方) 的值腺怯。
print(pow(2,3)) #pow冪運(yùn)算 == 2**3
print(pow(3,2))
print(pow(2,3,3)) #冪運(yùn)算之后再取余
print(pow(3,2,1)) #冪運(yùn)算之后再取余
執(zhí)行結(jié)果:
8
9
2
0
5) sum
sum() 方法對(duì)系列進(jìn)行求和計(jì)算。
ret = sum([1,2,3,4,5,6])
print(ret)
ret = sum([1,2,3,4,5,6],10)
print(ret)
ret = sum([1,2,3,4,5,6,10],)
print(ret)
執(zhí)行結(jié)果:
21
31
31
6)min
min() 方法返回給定參數(shù)的最小值川无,參數(shù)可以為序列呛占。
print(min([1,2,3,4]))
print(min(1,2,3,4))
print(min(1,2,3,-4))
print(min(1,2,3,-4,key = abs)) # 以絕對(duì)值方式求最小值
執(zhí)行結(jié)果:
1
1
-4
1
7)max
max() 方法返回給定參數(shù)的最大值,參數(shù)可以為序列懦趋。
print(max([1,2,3,4]))
print(max(1,2,3,4))
print(max(1,2,3,-4))
print(max(1,2,3,-4,key = abs)) # 以絕對(duì)值方式求最大值
執(zhí)行結(jié)果:
4
4
3
-4
5.2 和數(shù)據(jù)結(jié)構(gòu)相關(guān)
5.2.1 序列
5.2.2 列表list和元組tuple
5.2.3 相關(guān)內(nèi)置函數(shù)
- reversed()
保留原列表晾虑,返回一個(gè)反向的迭代器
范例1:
l = [1,2,3,4,5]
l.reverse()
print(l)
l = [1,2,3,4,5]
l2 = reversed(l)
print(l2)
執(zhí)行結(jié)果:
[5, 4, 3, 2, 1]
<list_reverseiterator object at 0x000001EFBC521898>
2) slice()
slice() 函數(shù)實(shí)現(xiàn)切片對(duì)象,主要用在切片操作函數(shù)里的參數(shù)傳遞。
l = (1,2,23,213,5612,342,43)
sli = slice(1,5,2)
print(l[sli])
執(zhí)行結(jié)果
(2, 213)
5.2.4 字符串
- format()
format 函數(shù)可以接受不限個(gè)參數(shù)帜篇,位置可以不按順序糙捺。
范例:
print(format('test', '<20'))
print(format('test', '>20'))
print(format('test', '^20'))
執(zhí)行結(jié)果:
test
test
test
- bytes()
bytes 函數(shù) 轉(zhuǎn)換成bytes類(lèi)型
范例:
我拿到的是gbk編碼的,我想轉(zhuǎn)成utf-8編碼
print(bytes('你好',encoding='GBK')) # unicode轉(zhuǎn)換成GBK的bytes
print(bytes('你好',encoding='utf-8')) # unicode轉(zhuǎn)換成utf-8的bytes
print(bytes('你好',encoding='GBK').decode('GBK'))
執(zhí)行結(jié)果:
b'\xc4\xe3\xba\xc3'
b'\xe4\xbd\xa0\xe5\xa5\xbd'
你好
網(wǎng)絡(luò)編程 只能傳二進(jìn)制
照片和視頻也是以二進(jìn)制存儲(chǔ)
html網(wǎng)頁(yè)爬取到的也是編碼
- bytearray()
bytearray() 方法返回一個(gè)新字節(jié)數(shù)組笙隙。這個(gè)數(shù)組里的元素是可變的洪灯,并且每個(gè)元素的值范圍: 0 <= x < 256。
范例:
b_array = bytearray('你好',encoding='utf-8')
print(b_array)
print(b_array[0])
執(zhí)行結(jié)果:
bytearray(b'\xe4\xbd\xa0\xe5\xa5\xbd')
228
- memoryview()
memoryview() 函數(shù)返回給定參數(shù)的內(nèi)存查看對(duì)象(Momory view)竟痰。
切片 —— 字節(jié)類(lèi)型 不占內(nèi)存
字節(jié) —— 字符串 占內(nèi)存
- ord()與chr()
ord():字符按照unicode轉(zhuǎn)數(shù)字
chr():數(shù)字按照unicode轉(zhuǎn)字符
范例:
print(ord('a'))
print(ord('2'))
print(chr(97))
print(chr(50))
執(zhí)行結(jié)果:
97
50
a
2
- ascii()
只要是ascii碼中的內(nèi)容签钩,就打印出來(lái),不是就轉(zhuǎn)換成\u
范例:
print(ascii('好'))
print(ascii('1'))
執(zhí)行結(jié)果:
'\u597d'
'1'
- repr() 用于%r格式化輸出
name = 'egg'
print('你好%s'%name)
print('你好%r'%name)
print(repr('1'))
print(repr(1))
執(zhí)行結(jié)果:
你好egg
你好'egg'
'1'
1
5.2.2 數(shù)據(jù)集合
5.2.3 字典dict
5.2.4 集合set與frozenset
5.2.3 相關(guān)內(nèi)置函數(shù)
- len()
Python len() 方法返回對(duì)象(字符坏快、列表铅檩、元組等)長(zhǎng)度或項(xiàng)目個(gè)數(shù)。
- enumerate()
enumerate() 函數(shù)用于將一個(gè)可遍歷的數(shù)據(jù)對(duì)象(如列表莽鸿、元組或字符串)組合為一個(gè)索引序列昧旨,同時(shí)列出數(shù)據(jù)和數(shù)據(jù)下標(biāo),一般用在 for 循環(huán)當(dāng)中祥得。
Python 2.3. 以上版本可用兔沃,2.6 添加 start 參數(shù)。
- all()
判斷是否有bool值為False的值
范例:
print(all(['a','',123]))
print(all(['a',123]))
print(all([0,123]))
執(zhí)行結(jié)果:
False
True
False
- any()
判斷是否有bool值為T(mén)rue的值
范例:
print(any(['',True,0,[]]))
執(zhí)行結(jié)果:
True
- zip()
返回一個(gè)迭代器
范例1:
l = [1,2,3]
l2 = ["a","b","c"]
for i in zip(l,l2):
print(i)
執(zhí)行結(jié)果:
(1, 'a')
(2, 'b')
(3, 'c')
范例2:
l = [1,2,3,4,5]
l2 = ['a','b','c','d']
l3 = ('*','**',[1,2])
d = {'k1':1,'k2':2}
for i in zip(l,l2,l3,d):
print(i)
執(zhí)行結(jié)果:
(1, 'a', '*', 'k1')
(2, 'b', '**', 'k2')
- filter()
filter() 函數(shù)用于過(guò)濾序列级及,過(guò)濾掉不符合條件的元素粘拾,返回由符合條件元素組成的新列表。
范例1:
ret = filter(is_odd,[1,4,6,7,9,12,17]) # 相當(dāng)于[i for i in [1,4,6,7,9,12,17] if i % 2 ==1]
print(ret)
for i in ret:
print(i)
執(zhí)行結(jié)果:
<filter object at 0x0000015EEEE919B0>
1
7
9
17
范例2:
def is_str(s):
if type(s) == str:
return True
ret = filter(is_str,[1,"hello",6,7,"world",12,17])
for i in ret:
print(i)
執(zhí)行結(jié)果:
hello
world
范例3:
def is_str(s):
return type(s) == str
ret = filter(is_str,[1,"hello",6,7,"world",12,17])
for i in ret:
print(i)
執(zhí)行結(jié)果:
hello
world
范例4:
刪除none或者空字符串
def is_str(s):
return s and str(s).strip()
ret = filter(is_str, [1, 'hello','',' ',None,[], 6, 7, 'world', 12, 17])
for i in ret:
print(i)
執(zhí)行結(jié)果:
1
hello
6
7
world
12
17
范例5:
請(qǐng)利用filter()過(guò)濾出1~100中平方根是整數(shù)的數(shù)创千,即結(jié)果應(yīng)該是:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
# 開(kāi)平方實(shí)例:
from math import sqrt
print(sqrt(64))
執(zhí)行結(jié)果:
8.0
正式例子:
from math import sqrt
def func(num):
res = sqrt(num)
return res % 1 == 0
ret = filter(func,range(1,101))
for i in ret:
print(i)
執(zhí)行結(jié)果:
1
4
9
16
25
36
49
64
81
100
- map()
map() 會(huì)根據(jù)提供的函數(shù)對(duì)指定序列做映射缰雇。
范例:
求絕對(duì)值
ret = map(abs,[1,-4,6,-8])
print(ret)
for i in ret:
print(i)
執(zhí)行結(jié)果:
<map object at 0x00000153FCF818D0>
1
4
6
8
filter與map比較
filter 執(zhí)行了filter之后的結(jié)果集合 <= 執(zhí)行之前的個(gè)數(shù)
filter只管篩選,不會(huì)改變?cè)瓉?lái)的值
map 執(zhí)行前后元素個(gè)數(shù)不變
值可能發(fā)生改變
- sorted()
sorted() 函數(shù)對(duì)所有可迭代的對(duì)象進(jìn)行排序操作追驴。
范例1:sort
l = [1,-4,6,5,-10]
l.sort()
print(l)
執(zhí)行結(jié)果:
[-10, -4, 1, 5, 6]
范例2:sort
l = [1,-4,6,5,-10]
l.sort(key = abs) # 在原列表的基礎(chǔ)上進(jìn)行排序
print(l)
執(zhí)行結(jié)果:
[1, -4, 5, 6, -10]
范例3:sorted
l = [1,-4,6,5,-10]
print(sorted(l)) # 生成了一個(gè)新列表 不改變?cè)斜?占內(nèi)存
print(l)
執(zhí)行結(jié)果:
[-10, -4, 1, 5, 6]
[1, -4, 6, 5, -10]
范例4:sorted
l = [1,-4,6,5,-10]
print(sorted(l,key=abs,reverse=True))
print(l)
執(zhí)行結(jié)果:
[-10, 6, 5, -4, 1]
[1, -4, 6, 5, -10]
范例5:
列表按照每一個(gè)元素的len排序
l = [' ',[1,2],'hello world']
new_l = sorted(l,key=len)
print(new_l)
執(zhí)行結(jié)果:
[[1, 2], ' ', 'hello world']