一线脚、介紹
Python解釋器運行時會自動加載builtins
模塊泻轰,而我們常用的內(nèi)置函數(shù)都是在此模塊中残黑;
- 通過globals()查看當(dāng)前自帶模塊
>>> globals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>}
- 通過dir()查看builtins模塊內(nèi)置的函數(shù),通過len()計算有153個內(nèi)置屬性条舔,其中大約80多內(nèi)置函數(shù),60多個內(nèi)置異常乏矾,還有幾個內(nèi)置常數(shù)逞刷,特殊名稱以及模塊相關(guān)的屬性;
len(dir(__builtins__))
- 內(nèi)置函數(shù)
abs() | dict() | help() | min() | setattr() |
---|---|---|---|---|
all() | dir() | hex() | next() | slice() |
any() | divmod() | id() | object() | sorted() |
ascii() | enumerate() | input() | oct() | staticmethod() |
bin() | eval() | int() | open() | str() |
bool() | exec() | isinstance() | ord() | sum() |
bytearray() | filter() | issubclass() | pow() | super() |
bytes() | float() | iter() | print() | tuple() |
callable() | format() | len() | property() | type() |
chr() | frozenset() | list() | range() | vars() |
classmethod() | getattr() | locals() | repr() | zip() |
compile() | globals() | map() | reversed() | _import_() |
complex() | hasattr() | max() | round() | |
delattr() | hash() | memoryview() | set() |
- abs()絕對值函數(shù)
>>> abs(-100)
100
- dict() 創(chuàng)建字典
>>> dict(abc='123')
{'abc': '123'}
>>> dict()
{}
- help()幫助函數(shù)妻熊,查看函數(shù)或者模塊的使用方法
>>> help()
help> keywords
- min()函數(shù)夸浅,返回最小值
>>> min(1, 2, 3)
1
- setattr()函數(shù),跟類有關(guān)扔役,后續(xù)補充
- all()函數(shù)帆喇,判斷元組或列表內(nèi)元素是否為True,如果有一個不為True那么結(jié)果為False
>>> a = [1, 2, 3]
>>> all(a)
True
>>> b = [0, 1, 2]
>>> all(b)
False
- dir()函數(shù)不帶參數(shù)時亿胸,返回當(dāng)前范圍內(nèi)的變量坯钦、方法和定義的類型列表;帶參數(shù)時侈玄,返回參數(shù)的屬性婉刀、方法列表
dir()
['A', '__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'a', 'b']
>>> dir(a)
['__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']
- hex()函數(shù),將十進制轉(zhuǎn)換為十六進制
>>> hex(10)
'0xa'
- next()函數(shù)序仙,返回迭代器中下一個元素值
>>> number = '178582258'
>>> it = iter(number)
>>> next(it)
'1'
>>> next(it)
'7'
- slice()突颊, 返回切片類型的對象
>>> myslice = slice(5)
>>> myslice
slice(None, 5, None)
>>> arr = range(10)
>>> arr[myslice]
range(0, 5)
- any(),與all()相反,判斷元組或列表內(nèi)元素是否為False律秃,如果有一個不為False那么結(jié)果為True
>>> any([0, 0, 0])
False
>>> any([0, 1, 2])
True
- divmod()爬橡,計算兩個值相除,返回商和余數(shù)
>>> divmod(3, 1)
(3, 0)
>>> divmod(3, 2)
(1, 1)
- id()棒动,獲取對象的內(nèi)存地址
>>> id(3)
1876484912
- object()糙申,該方法不接收任何參數(shù),返回一個沒有任何功能的對象船惨。object是Python所有類的基類柜裸。
- sorted(),排序函數(shù)
>>> sorted([88, 2, 44, 51, 2231, 5, 111, 41])
[2, 5, 41, 44, 51, 88, 111, 2231]
>>> sorted((88, 2, 44, 51, 2231, 5, 111, 41))
[2, 5, 41, 44, 51, 88, 111, 2231]
- ascii()粱锐,打印函數(shù)疙挺,類似于print()方法
>>> ascii('abc')
"'abc'"
>>> ascii(2)
'2'
- enumerate(), 枚舉函數(shù)卜范,可用for循環(huán)打印出列表元素以及對應(yīng)的下標(biāo)
>>> a = ['lain', 'tom', 'lili', 'sunne']
>>> for i in enumerate(a):
print(i)
(0, 'lain')
(1, 'tom')
(2, 'lili')
(3, 'sunne')
- input()衔统,輸入函數(shù)
>>> input('姓名: ')
姓名: LAIN
'LAIN'
- oct(),講十進制轉(zhuǎn)成八進制
>>> oct(222)
'0o336'
- staticmethod()海雪,跟類有關(guān)葬荷,后續(xù)補充
- bin()陪每,講十進制轉(zhuǎn)成二進制
>>> bin(333)
'0b101001101'
>>> bin(2)
'0b10'
- eval(),執(zhí)行字符串表達式,并返回結(jié)果
>>> eval(('7 + 1'))
8
- int()锅很,將字符串或者數(shù)字轉(zhuǎn)換成整型叫倍,可指定進制數(shù)
>>> int('22', 8)
18
>>> int('22', 16)
34
>>> int('22', 10)
22
- open()幕庐,文件操作解愤,打開或者創(chuàng)建文件等;
- str()侠鳄, 更改類型為字符串
>>> type(str({'name1':'lain', 'name2':'lilei', 'name3':'tom'}))
<class 'str'>
>>> type({'name1':'lain', 'name2':'lilei', 'name3':'tom'})
<class 'dict'>
- bool()埠啃,返回布爾值
>>> bool()
False
>>> bool(2)
True
- exec(),執(zhí)行儲存在字符串或文件中的 Python 語句伟恶,相比于 eval碴开,exec可以執(zhí)行更復(fù)雜的 Python 代碼
>>> exec('print("hello world")')
hello world
- isinstance(),判斷對象是否屬于某個數(shù)據(jù)類型
>>> isinstance('1', int)
False
>>> isinstance(1, int)
True
- ord()博秫,返回ascii碼表上的數(shù)字
>>> ord('A')
65
>>> ord('a')
97
- sum()潦牛,求和
>>> sum([1, 2, 3])
6
>>> sum((2, 3, 4))
9
- bytearray(),返回一個新字節(jié)數(shù)組挡育。這個數(shù)組里的元素是可變的巴碗,并且每個元素的值范圍: 0 <= x < 256
如果 source 為整數(shù),則返回一個長度為 source 的初始化數(shù)組即寒;
如果 source 為字符串橡淆,則按照指定的 encoding 將字符串轉(zhuǎn)換為字節(jié)序列召噩;
如果 source 為可迭代類型,則元素必須為[0 ,255] 中的整數(shù)明垢;
如果 source 為與 buffer 接口一致的對象蚣常,則此對象也可以被用于初始化 bytearray市咽。
如果沒有輸入任何參數(shù)痊银,默認就是初始化數(shù)組為0個元素。
>>> bytearray([1, 2, 3])
bytearray(b'\x01\x02\x03')
>>> bytearray('jianshu.com', 'utf-8')
bytearray(b'jianshu.com')
- filter() 函數(shù)用于過濾序列施绎,過濾掉不符合條件的元素溯革,返回一個迭代器對象,如果要轉(zhuǎn)換為列表谷醉,可以使用 list() 來轉(zhuǎn)換致稀。該接收兩個參數(shù),第一個為函數(shù)俱尼,第二個為序列抖单,序列的每個元素作為參數(shù)傳遞給函數(shù)進行判,然后返回 True 或 False遇八,最后將返回 True 的元素放到新列表中
def is_odd(n):
return n % 2 == 1
tmplist = filter(is_odd, [1, 2, 3, 4, 5])
newlist = list(tmplist)
print(tmplist)
print(newlist)
執(zhí)行結(jié)果:
<filter object at 0x021195F0>
[1, 3, 5]
- issubclass()矛绘,類相關(guān)函數(shù)后續(xù)補充
- pow(),冪函數(shù)
>>> pow(2, 2)
4
>>> pow(2, 3)
8
- super()刃永,類相關(guān)函數(shù)后續(xù)補充
- bytes()货矮,將對象類型轉(zhuǎn)換為字節(jié)
>>> bytes(2)
b'\x00\x00'
>>> bytes('i', encoding='utf-8')
b'i'
- float(),將對象類型轉(zhuǎn)換為浮點數(shù)
>>> float(100)
100.0
>>> float(-12)
-12.0
- iter()斯够,生成迭代器囚玫,使其具備next()功能
>>> a = [1, 2, 3]
>>> b = iter(a)
>>> next(b)
1
>>> next(b)
2
>>> next(b)
3
- print(),打印函數(shù)
>>> print('Hello World')
Hello World
- tuple()读规,將對象轉(zhuǎn)換成元組類型
>>> tuple()
()
>>> tuple('lain')
('l', 'a', 'i', 'n')
>>> tuple(['lain', 'baidu', 'FB', 'alibaba'])
('lain', 'baidu', 'FB', 'alibaba')
- callable()抓督,判斷對象是否可以被調(diào)用
>>> callable(0)
False
>>> callable('lain')
False
>>> def add(a):
print(a)
>>> callable(add)
True
- format(),字符串格式化
>>> print('my name is {0}'.format('lain'))
my name is lain
len()束亏,計算長度或者元素個數(shù)
>>> len('jianshu.com')
11
>>> len(['lain', 'baidu', 'FB', 'alibaba'])
4
- property()铃在,類相關(guān)函數(shù)后續(xù)補充
type(),查看對象數(shù)據(jù)類型
>>> type(3)
<class 'int'>
>>> type(['lain', 23, 'shenzhen'])
<class 'list'>
- chr()枪汪,與ord相反涌穆,給出ascii碼表中對應(yīng)得數(shù)字,返回字符
>>> ord('a')
97
>>> chr(97)
'a'
- frozenset()雀久,創(chuàng)建冰凍集合此集合不可增刪改
>>> frozenset([2, 3, 4, 6])
frozenset({2, 3, 4, 6})
- list()宿稀,將對象轉(zhuǎn)換成列表
>>> list('hello world')
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
- range(),返回可迭代對象
>>> range(10)
range(0, 10)
- vars()赖捌,返回字典
>>> x = 1
>>> scope = vars()
>>> scope["x"]
1
- classmethod()祝沸,類相關(guān)函數(shù)后續(xù)補充
- getattr()矮烹,類相關(guān)函數(shù)后續(xù)補充
- locals(),返回當(dāng)前作用域下局部變量
locals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'a': 1, 'b': 2, 'add': <function add at 0x02E6DA50>, 'x': 1, 'scope': {...}}
- repr()罩锐,類似print打印
>>> repr(a)
'1'
- zip()奉狈,用于將可迭代的對象作為參數(shù),將對象中對應(yīng)的元素打包成一個個元組涩惑,然后返回由這些元組組成的對象仁期,這樣做的好處是節(jié)約了不少的內(nèi)存
>>> a = [1, 2, 3, 4, 5]
>>> b = ['a', 'b', 'c', 'd', 'e']
>>> list(zip(a, b))
[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')]
- compile(),將一個字符串編譯為字節(jié)代碼
>>> a = '3 + 6'
>>> eval(compile(a, '', 'eval'))
9
- globals()竭恬,會以字典類型返回當(dāng)前位置的全部全局變量
>>> globals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'a': '3 + 6', 'b': ['a', 'b', 'c', 'd', 'e'], 'add': <function add at 0x02E6DA50>, 'x': 1, 'scope': {...}}
- map()跛蛋,會根據(jù)提供的函數(shù)對指定序列做映射,第一個參數(shù) function 以參數(shù)序列中的每一個元素調(diào)用 function 函數(shù)痊硕,返回包含每次 function 函數(shù)返回值的新列表
calc = lambda x, y: x * y
data = map(calc, [1, 2, 3, 4, 5], [6, 7, 8, 9, 10]) #將第一個列表和第二個列表分別當(dāng)做參數(shù)x赊级,y
for i in data:
print(i,end=' ')
運行結(jié)果:
6 14 24 36 50
- reversed(),返回一個反轉(zhuǎn)的迭代器
<class 'reversed'>
>>> reversed([1, 2, 4])
<list_reverseiterator object at 0x02E4EAD0>
>>> a = reversed([1, 2, 3, 5]) #list結(jié)果是一個反轉(zhuǎn)的列表迭代器
>>> list(a)
[5, 3, 2, 1]
>>> list(a) #第二次list就是空
[]
>>> type(a)
<class 'list_reverseiterator'>
- import()岔绸,動態(tài)加載類或者函數(shù)以及模塊
>>> __import__('time') #類似于import time
<module 'time' (built-in)>
>>> import time
- complex()理逊,用于創(chuàng)建一個值為 real + imag * j 的復(fù)數(shù)或者轉(zhuǎn)化一個字符串或數(shù)為復(fù)數(shù)。如果第一個參數(shù)為字符串盒揉,則不需要指定第二個參數(shù)
>>> complex(1, 2)
(1+2j)
>>> complex('1')
(1+0j)
>>> complex('1+2j')
(1+2j)
- hasattr()晋被,類相關(guān)函數(shù)后續(xù)補充
- max(),返回最大值
>>> max([1, 2, 3, 4])
4
>>> max(1, 2, 3, 5)
5
- round()预烙,四舍五入墨微,可以指定小數(shù)位數(shù)
>>> round(3.4)
3
>>> round(4.6)
5
>>> round(3.1415926, 3)
3.142
>>> round(3.1415926, 2)
3.14
- delattr(),類相關(guān)函數(shù)后續(xù)補充
- hash()扁掸,返回對象的哈希值
>>> hash('jianshu.com')
1705446308
>>> hash(15278569)
15278569
- memoryview()翘县,返回obj的內(nèi)存視圖對象;obj只能是bytes或bytesarray類型
>>> a = memoryview(b'jianshu.com')
>>> a[:]
<memory at 0x02E3E6B0>
- set()谴分,將對象轉(zhuǎn)換為集合
>>> a = set([1, 2, 3, 4, 5])
>>> type(a)
<class 'set'>
>>> type(set())
<class 'set'>
>>> type(set('hello world'))
<class 'set'>