Python內(nèi)置函數(shù)(63個(gè))
1.abs()
絕對(duì)值或復(fù)數(shù)的模
In [1]: abs(-6)
Out[1]: 6
2.all()
接受一個(gè)迭代器月腋,如果迭代器的所有元素都為真岳链,那么返回True矾策,否則返回False
In [2]: all([1,0,3,6])
Out[2]: False
In [3]: all([1,2,3])
Out[3]: True
3.any()
接受一個(gè)迭代器稿黄,如果迭代器里有一個(gè)元素為真尝苇,那么返回True愧旦,否則返回False
In [4]: any([0,0,0,[]])
Out[4]: False
In [5]: any([0,0,1])
Out[5]: True
4.ascii()
調(diào)用對(duì)象的repr() 方法世剖,獲得該方法的返回值
In [30]: class Student():
...: def __init__(self,id,name):
...: self.id = id
...: self.name = name
...: def __repr__(self):
...: return 'id = '+self.id +', name = '+self.name
In [32]: xiaoming = Student('01','xiaoming')
In [33]: print(xiaoming)
id = 001, name = xiaoming
In [34]: ascii(xiaoming)
Out[34]: 'id = 001, name = xiaoming'
5.bin()
將十進(jìn)制轉(zhuǎn)換為二進(jìn)制
In [35]: bin(10)
Out[35]: '0b1010'
6.oct()
將十進(jìn)制轉(zhuǎn)換為八進(jìn)制
In [36]: oct(9)
Out[36]: '0o11'
7.hex()
將十進(jìn)制轉(zhuǎn)換為十六進(jìn)制
In [37]: hex(15)
Out[37]: '0xf'
8.bool()
測(cè)試一個(gè)對(duì)象是True, 還是False.
In [38]: bool([0,0,0])
Out[38]: True
In [39]: bool([])
Out[39]: False
In [40]: bool([1,0,1])
Out[40]: True
9.bytes()
將一個(gè)字符串轉(zhuǎn)換成字節(jié)類型
In [44]: s = "apple"
In [45]: bytes(s,encoding='utf-8')
Out[45]: b'apple'
10.str()
將字符類型
、數(shù)值類型
等轉(zhuǎn)換為字符串類型
In [46]: integ = 100
In [47]: str(integ)
Out[47]: '100'
11.callable()
判斷對(duì)象是否可以被調(diào)用笤虫,能被調(diào)用的對(duì)象就是一個(gè)callable 對(duì)象旁瘫,比如函數(shù) str, int 等都是可被調(diào)用的,但是例子4
中xiaoming
這個(gè)實(shí)例是不可被調(diào)用的:
In [48]: callable(str)
Out[48]: True
In [49]: callable(int)
Out[49]: True
In [50]: xiaoming
Out[50]: id = 001, name = xiaoming
In [51]: callable(xiaoming)
Out[51]: False
12.chr()
查看十進(jìn)制整數(shù)對(duì)應(yīng)的ASCII字符
In [54]: chr(65)
Out[54]: 'A'
13.ord()
查看某個(gè)ascii對(duì)應(yīng)的十進(jìn)制數(shù)
In [60]: ord('A')
Out[60]: 65
14.classmethod()
classmethod 修飾符對(duì)應(yīng)的函數(shù)不需要實(shí)例化琼蚯,不需要 self 參數(shù)酬凳,但第一個(gè)參數(shù)需要是表示自身類的 cls 參數(shù),可以來(lái)調(diào)用類的屬性遭庶,類的方法宁仔,實(shí)例化對(duì)象等。
In [66]: class Student():
...: def __init__(self,id,name):
...: self.id = id
...: self.name = name
...: def __repr__(self):
...: return 'id = '+self.id +', name = '+self.name
...: @classmethod
...: def f(cls):
...: print(cls)
15.complie()
將字符串編譯成python 能識(shí)別或可以執(zhí)行的代碼峦睡,也可以將文字讀成字符串再編譯翎苫。
In [74]: s = "print('helloworld')"
In [75]: r = compile(s,"<string>", "exec")
In [76]: r
Out[76]: <code object <module> at 0x0000000005DE75D0, file "<string>", line 1>
In [77]: exec(r)
helloworld
16.complex()
創(chuàng)建一個(gè)復(fù)數(shù)
In [81]: complex(1,2)
Out[81]: (1+2j)
17.delattr()
刪除對(duì)象的屬性
In [87]: delattr(xiaoming,'id')
In [88]: hasattr(xiaoming,'id')
Out[88]: False
18.dict()
創(chuàng)建數(shù)據(jù)字典
In [92]: dict()
Out[92]: {}
In [93]: dict(a='a',b='b')
Out[93]: {'a': 'a', 'b': 'b'}
In [94]: dict(zip(['a','b'],[1,2]))
Out[94]: {'a': 1, 'b': 2}
In [95]: dict([('a',1),('b',2)])
Out[95]: {'a': 1, 'b': 2}
19.dir()
不帶參數(shù)時(shí)返回當(dāng)前范圍內(nèi)的變量,方法和定義的類型列表榨了;帶參數(shù)時(shí)返回參數(shù)的屬性煎谍,方法列表。
In [96]: dir(xiaoming)
Out[96]:
['__class__',
'__delattr__',
'__dict__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__gt__',
'__hash__',
'__init__',
'__init_subclass__',
'__le__',
'__lt__',
'__module__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__setattr__',
'__sizeof__',
'__str__',
'__subclasshook__',
'__weakref__',
'name']
20.divmod()
分別取商和余數(shù)
In [97]: divmod(10,3)
Out[97]: (3, 1)
21.enumerate()
返回一個(gè)可以枚舉的對(duì)象龙屉,該對(duì)象的next()方法將返回一個(gè)元組呐粘。
In [98]: s = ["a","b","c"]
...: for i ,v in enumerate(s,1):
...: print(i,v)
...:
1 a
2 b
3 c
22.eval()
將字符串str 當(dāng)成有效的表達(dá)式來(lái)求值并返回計(jì)算結(jié)果取出字符串中內(nèi)容
In [99]: s = "1 + 3 +5"
...: eval(s)
...:
Out[99]: 9
23.exec()
執(zhí)行字符串或complie方法編譯過(guò)的字符串,沒(méi)有返回值
In [74]: s = "print('helloworld')"
In [75]: r = compile(s,"<string>", "exec")
In [76]: r
Out[76]: <code object <module> at 0x0000000005DE75D0, file "<string>", line 1>
In [77]: exec(r)
helloworld
24.filter()
過(guò)濾器,構(gòu)造一個(gè)序列事哭,等價(jià)于
[ item for item in iterables if function(item)]
在函數(shù)中設(shè)定過(guò)濾條件漫雷,逐一循環(huán)迭代器中的元素,將返回值為T(mén)rue時(shí)的元素留下鳍咱,形成一個(gè)filter類型數(shù)據(jù)降盹。
In [101]: fil = filter(lambda x: x>10,[1,11,2,45,7,6,13])
In [102]: list(fil)
Out[102]: [11, 45, 13]
25.float()
將一個(gè)字符串或整數(shù)轉(zhuǎn)換為浮點(diǎn)數(shù)
In [103]: float(3)
Out[103]: 3.0
26.format()
格式化輸出字符串,format(value, format_spec)實(shí)質(zhì)上是調(diào)用了value的format(format_spec)方法谤辜。
In [104]: print("i am {0},age{1}".format("tom",18))
i am tom,age18
27.frozenset()
創(chuàng)建一個(gè)不可修改的集合蓄坏。
In [105]: frozenset([1,1,3,2,3])
Out[105]: frozenset({1, 2, 3})
28.getattr()
獲取對(duì)象的屬性
In [106]: getattr(xiaoming,'name')
Out[106]: 'xiaoming'
29.globals()
返回一個(gè)描述當(dāng)前全局變量的字典
30.hasattr()
In [110]: hasattr(xiaoming,'name')
Out[110]: True
In [111]: hasattr(xiaoming,'id')
Out[111]: False
31.hash()
返回對(duì)象的哈希值
In [112]: hash(xiaoming)
Out[112]: 6139638
32.help()
返回對(duì)象的幫助文檔
In [113]: help(xiaoming)
Help on Student in module __main__ object:
class Student(builtins.object)
| Methods defined here:
|
| __init__(self, id, name)
|
| __repr__(self)
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
33.id()
返回對(duì)象的內(nèi)存地址
In [115]: id(xiaoming)
Out[115]: 98234208
34.input()
獲取用戶輸入內(nèi)容
In [116]: input()
aa
Out[116]: 'aa'
35.int()
int(x, base =10) , x可能為字符串或數(shù)值,將x 轉(zhuǎn)換為一個(gè)普通整數(shù)丑念。如果參數(shù)是字符串涡戳,那么它可能包含符號(hào)和小數(shù)點(diǎn)。如果超出了普通整數(shù)的表示范圍脯倚,一個(gè)長(zhǎng)整數(shù)被返回渔彰。
In [120]: int('12',16)
Out[120]: 18
36.isinstance(object, classinfo)
判斷object是否為類classinfo的實(shí)例,是返回true
In [20]: class Student():
...: ...: def __init__(self,id,name):
...: ...: self.id = id
...: ...: self.name = name
...: ...: def __repr__(self):
...: ...: return 'id = '+self.id +', name = '+self.name
...:
In [21]: xiaoming = Student('001','xiaoming')
In [22]: isinstance(xiaoming,Student)
Out[22]: True
37.issubclass(class, classinfo)
如果class是classinfo類的子類推正,返回True:
In [27]: class undergraduate(Student):
...: def studyClass(self):
...: pass
...: def attendActivity(self):
...: pass
...:
In [28]: issubclass(undergraduate,Student)
Out[28]: True
In [29]: issubclass(object,Student)
Out[29]: False
In [30]: issubclass(Student,object)
Out[30]: True
如果class是classinfo元組中某個(gè)元素的子類恍涂,也會(huì)返回True
In [26]: issubclass(int,(int,float))
Out[26]: True
38.iter(object, sentinel)
返回一個(gè)可迭代對(duì)象, sentinel可省略
In [72]: lst = [1,3,5]
In [73]: for i in iter(lst):
...: print(i)
...:
1
3
5
sentinel 理解為迭代對(duì)象的哨兵,一旦迭代到此元素植榕,立即終止:
In [81]: class TestIter(object):
...: def __init__(self):
...: self.l=[1,3,2,3,4,5]
...: self.i=iter(self.l)
...: def __call__(self): #定義了__call__方法的類的實(shí)例是可調(diào)用的
...: item = next(self.i)
...: print ("__call__ is called,which would return",item)
...: return item
...: def __iter__(self): #支持迭代協(xié)議(即定義有__iter__()函數(shù))
...: print ("__iter__ is called!!")
...: return iter(self.l)
...:
In [82]: t = TestIter()
...: t1 = iter(t, 3)
...: for i in t1:
...: print(i)
...:
__call__ is called,which would return 1
1
__call__ is called,which would return 3
39.len(s)
返回對(duì)象的長(zhǎng)度(元素個(gè)數(shù))
In [83]: dic = {'a':1,'b':3}
In [84]: len(dic)
Out[84]: 2
40.list([iterable])
返回可變序列類型
In [85]: list(map(lambda x: x%2==1, [1,3,2,4,1]))
Out[85]: [True, True, False, False, True]
41.map(function, iterable, …)
返回一個(gè)將 function 應(yīng)用于 iterable 中每一項(xiàng)并輸出其結(jié)果的迭代器:
In [85]: list(map(lambda x: x%2==1, [1,3,2,4,1]))
Out[85]: [True, True, False, False, True]
可以傳入多個(gè)iterable對(duì)象再沧,輸出長(zhǎng)度等于最短序列的長(zhǎng)度:
In [88]: list(map(lambda x,y: x%2==1 and y%2==0, [1,3,2,4,1],[3,2,1,2]))
Out[88]: [False, True, False, False]
42.max(iterable,*[, key, default])
返回最大值:
In [99]: max(3,1,4,2,1)
Out[99]: 4
In [100]: max((),default=0)
Out[100]: 0
In [89]: di = {'a':3,'b1':1,'c':4}
In [90]: max(di)
Out[90]: 'c'
In [102]: a = [{'name':'xiaoming','age':18,'gender':'male'},{'name':'
...: xiaohong','age':20,'gender':'female'}]
In [104]: max(a,key=lambda x: x['age'])
Out[104]: {'name': 'xiaohong', 'age': 20, 'gender': 'female'}
43.min(iterable,*[, key, default])
返回最小值
44.memoryview(obj)
返回由給定實(shí)參創(chuàng)建的“內(nèi)存視圖”對(duì)象, Python 代碼訪問(wèn)一個(gè)對(duì)象的內(nèi)部數(shù)據(jù)尊残,只要該對(duì)象支持 緩沖區(qū)協(xié)議 而無(wú)需進(jìn)行拷貝
45.next(iterator,[, default])
返回可迭代對(duì)象的下一個(gè)元素
In [129]: it = iter([5,3,4,1])
In [130]: next(it)
Out[130]: 5
In [131]: next(it)
Out[131]: 3
In [132]: next(it)
Out[132]: 4
In [133]: next(it)
Out[133]: 1
In [134]: next(it,0) #迭代到頭炒瘸,默認(rèn)返回值為0
Out[134]: 0
In [135]: next(it)
----------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-135-bc1ab118995a> in <module>
----> 1 next(it)
StopIteration:
46.object()
返回一個(gè)沒(méi)有特征的新對(duì)象。object 是所有類的基類寝衫。
In [137]: o = object()
In [138]: type(o)
Out[138]: object
47.open(file)
返回文件對(duì)象
In [146]: fo = open('D:/a.txt',mode='r', encoding='utf-8')
In [147]: fo.read()
Out[147]: '\ufefflife is not so long,\nI use Python to play.'
mode取值表:
字符 |
意義 |
'r' |
讀惹昀(默認(rèn)) |
'w' |
寫(xiě)入,并先截?cái)辔募?/td>
|
'x' |
排它性創(chuàng)建竞端,如果文件已存在則失敗 |
'a' |
寫(xiě)入屎即,如果文件存在則在末尾追加 |
'b' |
二進(jìn)制模式 |
't' |
文本模式(默認(rèn)) |
'+' |
打開(kāi)用于更新(讀取與寫(xiě)入) |
48.pow(base, exp[, mod])
base為底的exp次冪,如果mod給出事富,取余
In [149]: pow(3, 2, 4)
Out[149]: 1
49.print(objects)
打印對(duì)象技俐,此函數(shù)不解釋
50.class property(fget=None, fset=None, fdel=None, doc=None)
返回 property 屬性,典型的用法:
class C:
def __init__(self):
self._x = None
def getx(self):
return self._x
def setx(self, value):
self._x = value
def delx(self):
del self._x
# 使用property類創(chuàng)建 property 屬性
x = property(getx, setx, delx, "I'm the 'x' property.")
使用python裝飾器统台,實(shí)現(xiàn)與上完全一樣的效果代碼:
class C:
def __init__(self):
self._x = None
@property
def x(self):
return self._x
@x.setter
def x(self, value):
self._x = value
@x.deleter
def x(self):
del self._x
51.range(stop)
range(start, stop[,step])
生成一個(gè)不可變序列:
In [153]: range(11)
Out[153]: range(0, 11)
In [154]: range(0,11,1)
Out[154]: range(0, 11)
52.reversed(seq)
返回一個(gè)反向的 iterator:
In [155]: rev = reversed([1,4,2,3,1])
In [156]: for i in rev:
...: print(i)
...:
1
3
2
4
1
53.round(number[, ndigits])
四舍五入雕擂,ndigits代表小數(shù)點(diǎn)后保留幾位:
In [157]: round(10.0222222, 3)
Out[157]: 10.022
54.class set([iterable])
返回一個(gè)set對(duì)象,可實(shí)現(xiàn)去重:
In [159]: a = [1,4,2,3,1]
In [160]: set(a)
Out[160]: {1, 2, 3, 4}
55.class slice(stop)
class slice(start, stop[, step])
返回一個(gè)表示由 range(start, stop, step) 所指定索引集的 slice對(duì)象
In [170]: a = [1,4,2,3,1]
In [171]: a[slice(0,5,2)] #等價(jià)于a[0:5:2]
Out[171]: [1, 2, 1]
56.sorted(iterable, *, key=None, reverse=False)
排序:
In [174]: a = [1,4,2,3,1]
In [175]: sorted(a,reverse=True)
Out[175]: [4, 3, 2, 1, 1]
In [178]: a = [{'name':'xiaoming','age':18,'gender':'male'},{'name':'
...: xiaohong','age':20,'gender':'female'}]
In [180]: sorted(a,key=lambda x: x['age'],reverse=False)
Out[180]:
[{'name': 'xiaoming', 'age': 18, 'gender': 'male'},
{'name': 'xiaohong', 'age': 20, 'gender': 'female'}]
57. @``staticmethod`
將方法轉(zhuǎn)換為靜態(tài)方法贱勃,不做解釋
58.vars()
返回模塊井赌、類谤逼、實(shí)例或任何其它具有 __dict__
屬性的對(duì)象的 __dict__
屬性
In [2]: vars()
Out[2]:
{'__name__': '__main__',
'__doc__': 'Automatically created module for IPython interactive environment',
'__package__': None,
'__loader__': None,
'__spec__': None,
'__builtin__': <module 'builtins' (built-in)>,
'__builtins__': <module 'builtins' (built-in)>,
'_ih': ['', 'vars([1,2,3])', 'vars()'],
'_oh': {},
'_dh': ['C:\\Windows\\system32'],
'In': ['', 'vars([1,2,3])', 'vars()'],
'Out': {},
'get_ipython': <bound method InteractiveShell.get_ipython of <IPython.terminal.interactiveshell.TerminalInteractiveShell object at 0x0000026004D91C50>>,
'exit': <IPython.core.autocall.ExitAutocall at 0x26006011048>,
'quit': <IPython.core.autocall.ExitAutocall at 0x26006011048>,
'_': '',
'__': '',
'___': '',
'_i': 'vars([1,2,3])',
'_ii': '',
'_iii': '',
'_i1': 'vars([1,2,3])',
'_i2': 'vars()'}
59.sum(iterable, /, start=0)
求和:
In [181]: a = [1,4,2,3,1]
In [182]: sum(a)
Out[182]: 11
In [185]: sum(a,10) #求和的初始值為10
Out[185]: 21
60.super([type[, object-or-type]])
返回一個(gè)代理對(duì)象,它會(huì)將方法調(diào)用委托給 type 的父類或兄弟類
61.tuple([iterable])
雖然被稱為函數(shù)仇穗,但 tuple
實(shí)際上是一個(gè)不可變的序列類型
62.class type
(object)
class type
(name, bases, dict)
傳入一個(gè)參數(shù)時(shí)流部,返回 object 的類型:
In [186]: type(xiaoming)
Out[186]: __main__.Student
In [187]: type(tuple())
Out[187]: tuple
63.zip
(*iterables)
創(chuàng)建一個(gè)聚合了來(lái)自每個(gè)可迭代對(duì)象中的元素的迭代器:
In [188]: x = [3,2,1]
In [189]: y = [4,5,6]
In [190]: list(zip(y,x))
Out[190]: [(4, 3), (5, 2), (6, 1)]
In [191]: a = range(5)
In [192]: b = list('abcde')
In [193]: b
Out[193]: ['a', 'b', 'c', 'd', 'e']
In [194]: [str(y) + str(x) for x,y in zip(a,b)]
Out[194]: ['a0', 'b1', 'c2', 'd3', 'e4']