python常用內(nèi)置函數(shù)
數(shù)學(xué)運算(7個)
- abs()
- divmod()
- max()
- min()
- pow()
- round()
- sum()
# abs()
In [1]: abs(-2)
Out[1]: 2
# divmod()
In [1]: divmod(10, 3)
Out[1]: (3, 1)
In [2]: divmod(-100, 15)
Out[2]: (-7, 5)
In [3]: divmod(15.5, 10)
Out[3]: (1.0, 5.5)
In [4]: divmod(-20, 6.05)
Out[4]: (-4.0, 4.199999999999999)
# max() / min()
In [10]: max('absd')
Out[10]: 's'
In [11]: max('1234')
Out[11]: '4'
In [12]: max('1234abcd')
Out[12]: 'd'
In [13]: max('123abcABC')
Out[13]: 'c'
In [14]: min('123abcABC')
Out[14]: '1'
In [15]: max(1, '1', 'a')
Out[15]: 'a'
In [20]: max(-4, -2, key=abs)
Out[20]: -4
In [21]: min(-6, 2, key=abs)
Out[21]: 2
# pow()
In [16]: pow(2, 3) # 2**3
Out[16]: 8
In [17]: pow(-3, 3)
Out[17]: -27
In [18]: pow(2.5, 2)
Out[18]: 6.25
In [22]: pow(2, 3, 5) # (computed more efficiently than pow(x, y) % z)
Out[22]: 3
In [23]: pow(2, 3)%5
Out[23]: 3
# round()
In [25]: round(4.81)
Out[25]: 5.0
In [26]: round(4.81, 2)
Out[26]: 4.81
In [27]: round(3.1415926, 2)
Out[27]: 3.14
In [28]: round(3.1415926, 4)
Out[28]: 3.1416
In [29]: round(4, 2)
Out[29]: 4.0
In [30]: round(4.0000, 2)
Out[30]: 4.0
In [31]: round(4.00019, 3)
Out[31]: 4.0
In [32]: round(4.00019, 4)
Out[32]: 4.0002
# sum()
In [5]: sum([1, 2, 3])
Out[5]: 6
In [7]: sum((1, 2, 3), -4)
Out[7]: 2
In [8]: sum([1, 2, 3], -5)
Out[8]: 1
In [2]: sum(1, 2, 3)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-2-c44a16fb57bf> in <module>()
----> 1 sum(1, 2, 3)
TypeError: sum expected at most 2 arguments, got 3
## sum() usage:
sum(...)
sum(sequence[, start]) -> value
Returns the sum of a sequence of numbers (NOT strings) plus the value
of parameter 'start' (which defaults to 0). When the sequence is
empty, returns start.
類型轉(zhuǎn)換(24個)
- bool()
- int()
- float()
- complex()
- str()
- ord()
- chr()
- bin()
- oct()
- hex()
- tuple()
- list()
- dict()
- range()
>>> bool() #未傳入?yún)?shù)
False
>>> bool(0) #數(shù)值0钉汗、空序列等值為False
False
>>> bool(1)
True
>>> int() #不傳入?yún)?shù)時羹令,得到結(jié)果0。
0
>>> int(3)
3
>>> int(3.6)
3
>>> float() #不提供參數(shù)的時候损痰,返回0.0
0.0
>>> float(3)
3.0
>>> float('3')
3.0
>>> complex() #當(dāng)兩個參數(shù)都不提供時福侈,返回復(fù)數(shù) 0j。
0j
>>> complex('1+2j') #傳入字符串創(chuàng)建復(fù)數(shù)
(1+2j)
>>> complex(1,2) #傳入數(shù)值創(chuàng)建復(fù)數(shù)
(1+2j)
>>> str()
''
>>> str(None)
'None'
>>> str('abc')
'abc'
>>> str(123)
'123'
>>> bytearray('中文','utf-8')
bytearray(b'\xe4\xb8\xad\xe6\x96\x87')
>>> bytes('中文','utf-8')
b'\xe4\xb8\xad\xe6\x96\x87'
>>> v = memoryview(b'abcefg')
>>> v[1]
98
>>> v[-1]
103
>>> ord('a')
97
>>> chr(97) #參數(shù)類型為整數(shù)
'a'
>>> bin(3)
'0b11'
>>> oct(10)
'0o12'
>>> hex(15)
'0xf'
>>> tuple() #不傳入?yún)?shù)卢未,創(chuàng)建空元組
()
>>> tuple('121') #傳入可迭代對象肪凛。使用其元素創(chuàng)建新的元組
('1', '2', '1')
>>>list() # 不傳入?yún)?shù),創(chuàng)建空列表
[]
>>> list('abcd') # 傳入可迭代對象辽社,使用其元素創(chuàng)建新的列表
['a', 'b', 'c', 'd']
>>> dict() # 不傳入任何參數(shù)時伟墙,返回空字典。
{}
>>> dict(a = 1,b = 2) # 可以傳入鍵值對創(chuàng)建字典滴铅。
{'b': 2, 'a': 1}
>>> dict(zip(['a','b'],[1,2])) # 可以傳入映射函數(shù)創(chuàng)建字典戳葵。
{'b': 2, 'a': 1}
>>> dict((('a',1),('b',2))) # 可以傳入可迭代對象創(chuàng)建字典。
{'b': 2, 'a': 1}
>>>set() # 不傳入?yún)?shù)汉匙,創(chuàng)建空集合
set()
>>> a = set(range(10)) # 傳入可迭代對象拱烁,創(chuàng)建集合
>>> a
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
>>> a = frozenset(range(10))
>>> a
frozenset({0, 1, 2, 3, 4, 5, 6, 7, 8, 9})
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1)) #指定起始值
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
>>> a = range(10)
>>> b = range(1,10)
>>> c = range(1,10,3)
>>> a,b,c # 分別輸出a,b,c
(range(0, 10), range(1, 10), range(1, 10, 3))
>>> list(a),list(b),list(c) # 分別輸出a,b,c的元素
([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 4, 7])
>>> a = iter('abcd') #字符串序列
>>> a
<str_iterator object at 0x03FB4FB0>
>>> next(a)
'a'
>>> next(a)
'b'
>>> next(a)
'c'
>>> next(a)
'd'
>>> next(a)
Traceback (most recent call last):
File "<pyshell#29>", line 1, in <module>
next(a)
StopIteration
>>> c1 = slice(5) # 定義c1
>>> c1
slice(None, 5, None)
>>> c2 = slice(2,5) # 定義c2
>>> c2
slice(2, 5, None)
>>> c3 = slice(1,10,3) # 定義c3
>>> c3
slice(1, 10, 3)
#定義父類A
>>> class A(object):
def __init__(self):
print('A.__init__')
#定義子類B,繼承A
>>> class B(A):
def __init__(self):
print('B.__init__')
super().__init__()
#super調(diào)用父類方法
>>> b = B()
B.__init__
A.__init__
>>> a = object()
>>> a.name = 'kim' # 不能設(shè)置屬性
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
a.name = 'kim'
AttributeError: 'object' object has no attribute 'name'
序列操作(8個)
- all()
- any()
- filter()
- map()
- next()
- reversed()
- sorted()
- zip()
>>> all([1,2]) #列表中每個元素邏輯值均為True噩翠,返回True
True
>>> all([0,1,2]) #列表中0的邏輯值為False戏自,返回False
False
>>> all(()) #空元組
True
>>> all({}) #空字典
True
>>> any([0,1,2]) #列表元素有一個為True,則返回True
True
>>> any([0,0]) #列表元素全部為False伤锚,則返回False
False
>>> any([]) #空列表
False
>>> any({}) #空字典
False
>>> a = list(range(1,10)) #定義序列
>>> a
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> def if_odd(x): #定義奇數(shù)判斷函數(shù)
return x%2==1
>>> list(filter(if_odd,a)) #篩選序列中的奇數(shù)
[1, 3, 5, 7, 9]
>>> a = map(ord,'abcd')
>>> a
<map object at 0x03994E50>
>>> list(a)
[97, 98, 99, 100]
>>> a = iter('abcd')
>>> next(a)
'a'
>>> next(a)
'b'
>>> next(a)
'c'
>>> next(a)
'd'
>>> next(a)
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
next(a)
StopIteration
#傳入default參數(shù)后擅笔,如果可迭代對象還有元素沒有返回,則依次返回其元素值,如果所有元素已經(jīng)返回猛们,則返回default指定的默認(rèn)值而不拋出StopIteration 異常
>>> next(a,'e')
'e'
>>> next(a,'e')
'e'
>>> a = reversed(range(10)) # 傳入range對象
>>> a # 類型變成迭代器
<range_iterator object at 0x035634E8>
>>> list(a)
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>>> a = ['a','b','d','c','B','A']
>>> a
['a', 'b', 'd', 'c', 'B', 'A']
>>> sorted(a) # 默認(rèn)按字符ascii碼排序
['A', 'B', 'a', 'b', 'c', 'd']
>>> sorted(a,key = str.lower) # 轉(zhuǎn)換成小寫后再排序念脯,'a'和'A'值一樣,'b'和'B'值一樣
['a', 'A', 'b', 'B', 'c', 'd']
>>> x = [1,2,3] #長度3
>>> y = [4,5,6,7,8] #長度5
>>> list(zip(x,y)) # 取最小長度3
[(1, 4), (2, 5), (3, 6)]
對象操作(9個)
- help()
- dir() : 返回對象或者當(dāng)前作用域內(nèi)的屬性列表
- id() : 返回對象的唯一標(biāo)識符
- hash() : 獲取對象的哈希值
- type() : 返回對象的類型
- len() : 返回對象的長度
- ascii() : 返回對象的可打印表字符串表現(xiàn)形式
- format() : 格式化顯示值
- vars() : 返回當(dāng)前作用域內(nèi)的局部變量和其值組成的字典阅懦,或返回對象的屬性列表
>>> help(str)
Help on class str in module builtins:
class str(object)
| str(object='') -> str
| str(bytes_or_buffer[, encoding[, errors]]) -> str
|
| Create a new string object from the given object. If encoding or
| errors is specified, then the object must expose a data buffer
| that will be decoded using the given encoding and error handler.
| Otherwise, returns the result of object.__str__() (if defined)
| or repr(object).
| encoding defaults to sys.getdefaultencoding().
| errors defaults to 'strict'.
|
| Methods defined here:
|
| __add__(self, value, /)
| Return self+value.
|
***************************
>>> import math
>>> math
<module 'math' (built-in)>
>>> dir(math)
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']
>>> a = 'some text'
>>> id(a)
69228568
>>> hash('good good study')
1032709256
>>> type(1) # 返回對象的類型
<class 'int'>
#使用type函數(shù)創(chuàng)建類型D和二,含有屬性InfoD
>>> D = type('D',(A,B),dict(InfoD='some thing defined in D'))
>>> d = D()
>>> d.InfoD
'some thing defined in D'
>>> len('abcd') # 字符串
>>> len(bytes('abcd','utf-8')) # 字節(jié)數(shù)組
>>> len((1,2,3,4)) # 元組
>>> len([1,2,3,4]) # 列表
>>> len(range(1,5)) # range對象
>>> len({'a':1,'b':2,'c':3,'d':4}) # 字典
>>> len({'a','b','c','d'}) # 集合
>>> len(frozenset('abcd')) #不可變集合
>>> ascii(1)
'1'
>>> ascii('&')
"'&'"
>>> ascii(9000000)
'9000000'
>>> ascii('中文') #非ascii字符
"'\\u4e2d\\u6587'"
#字符串可以提供的參數(shù) 's' None
>>> format('some string','s')
'some string'
>>> format('some string')
'some string'
#整形數(shù)值可以提供的參數(shù)有 'b' 'c' 'd' 'o' 'x' 'X' 'n' None
>>> format(3,'b') #轉(zhuǎn)換成二進制
'11'
>>> format(97,'c') #轉(zhuǎn)換unicode成字符
'a'
>>> format(11,'d') #轉(zhuǎn)換成10進制
'11'
>>> format(11,'o') #轉(zhuǎn)換成8進制
'13'
>>> format(11,'x') #轉(zhuǎn)換成16進制 小寫字母表示
'b'
>>> format(11,'X') #轉(zhuǎn)換成16進制 大寫字母表示
'B'
>>> format(11,'n') #和d一樣
'11'
>>> format(11) #默認(rèn)和d一樣
'11'
#浮點數(shù)可以提供的參數(shù)有 'e' 'E' 'f' 'F' 'g' 'G' 'n' '%' None
>>> format(314159267,'e') #科學(xué)計數(shù)法,默認(rèn)保留6位小數(shù)
'3.141593e+08'
>>> format(314159267,'0.2e') #科學(xué)計數(shù)法耳胎,指定保留2位小數(shù)
'3.14e+08'
>>> format(314159267,'0.2E') #科學(xué)計數(shù)法惯吕,指定保留2位小數(shù),采用大寫E表示
'3.14E+08'
>>> format(314159267,'f') #小數(shù)點計數(shù)法怕午,默認(rèn)保留6位小數(shù)
'314159267.000000'
>>> format(3.14159267000,'f') #小數(shù)點計數(shù)法废登,默認(rèn)保留6位小數(shù)
'3.141593'
>>> format(3.14159267000,'0.8f') #小數(shù)點計數(shù)法,指定保留8位小數(shù)
'3.14159267'
>>> format(3.14159267000,'0.10f') #小數(shù)點計數(shù)法郁惜,指定保留10位小數(shù)
'3.1415926700'
>>> format(3.14e+1000000,'F') #小數(shù)點計數(shù)法堡距,無窮大轉(zhuǎn)換成大小字母
'INF'
#g的格式化比較特殊,假設(shè)p為格式中指定的保留小數(shù)位數(shù)兆蕉,先嘗試采用科學(xué)計數(shù)法格式化羽戒,得到冪指數(shù)exp,如果-4<=exp<p虎韵,則采用小數(shù)計數(shù)法易稠,并保留p-1-exp位小數(shù),否則按小數(shù)計數(shù)法計數(shù)包蓝,并按p-1保留小數(shù)位數(shù)
>>> format(0.00003141566,'.1g') #p=1,exp=-5 ==》 -4<=exp<p不成立驶社,按科學(xué)計數(shù)法計數(shù),保留0位小數(shù)點
'3e-05'
>>> format(0.00003141566,'.2g') #p=1,exp=-5 ==》 -4<=exp<p不成立测萎,按科學(xué)計數(shù)法計數(shù)亡电,保留1位小數(shù)點
'3.1e-05'
>>> format(0.00003141566,'.3g') #p=1,exp=-5 ==》 -4<=exp<p不成立,按科學(xué)計數(shù)法計數(shù)硅瞧,保留2位小數(shù)點
'3.14e-05'
>>> format(0.00003141566,'.3G') #p=1,exp=-5 ==》 -4<=exp<p不成立份乒,按科學(xué)計數(shù)法計數(shù),保留0位小數(shù)點腕唧,E使用大寫
'3.14E-05'
>>> format(3.1415926777,'.1g') #p=1,exp=0 ==》 -4<=exp<p成立冒嫡,按小數(shù)計數(shù)法計數(shù),保留0位小數(shù)點
'3'
>>> format(3.1415926777,'.2g') #p=1,exp=0 ==》 -4<=exp<p成立四苇,按小數(shù)計數(shù)法計數(shù),保留1位小數(shù)點
'3.1'
>>> format(3.1415926777,'.3g') #p=1,exp=0 ==》 -4<=exp<p成立方咆,按小數(shù)計數(shù)法計數(shù)月腋,保留2位小數(shù)點
'3.14'
>>> format(0.00003141566,'.1n') #和g相同
'3e-05'
>>> format(0.00003141566,'.3n') #和g相同
'3.14e-05'
>>> format(0.00003141566) #和g相同
'3.141566e-05'
#作用于類實例
>>> class A(object):
pass
>>> a.__dict__
{}
>>> vars(a)
{}
>>> a.name = 'Kim'
>>> a.__dict__
{'name': 'Kim'}
>>> vars(a)
{'name': 'Kim'}
反射操作(8個)
-
import() : 動態(tài)導(dǎo)入模塊
- isinstance() : 判斷對象是否是類,或類型元組中任意類元素的實例
- issubclass() : 判斷類是否是另一個類(或類型元組中任意類元素)的子類
- hasattr() : 檢查對象是否含有屬性
- getattr() : 獲取對象的屬性值
- setattr() : 設(shè)置對象的屬性值
- delattr() : 刪除對象的屬性
- callable() : 檢測對象是否可被調(diào)用
index = __import__('index')
index.sayHello()
>>> isinstance(1,int)
True
>>> isinstance(1,str)
False
>>> isinstance(1,(int,str))
True
>>> issubclass(bool,int)
True
>>> issubclass(bool,str)
False
>>> issubclass(bool,(str,int))
True
#定義類A
>>> class Student:
def __init__(self,name):
self.name = name
>>> s = Student('Aim')
>>> hasattr(s,'name') #a含有name屬性
True
>>> hasattr(s,'age') #a不含有age屬性
False
#定義類Student
>>> class Student:
def __init__(self,name):
self.name = name
>>> getattr(s,'name') #存在屬性name
'Aim'
>>> getattr(s,'age',6) #不存在屬性age,但提供了默認(rèn)值榆骚,返回默認(rèn)值
>>> getattr(s,'age') #不存在屬性age片拍,未提供默認(rèn)值,調(diào)用報錯
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
getattr(s,'age')
AttributeError: 'Stduent' object has no attribute 'age'
>>> class Student:
def __init__(self,name):
self.name = name
>>> a = Student('Kim')
>>> a.name
'Kim'
>>> setattr(a,'name','Bob')
>>> a.name
'Bob'
#定義類A
>>> class A:
def __init__(self,name):
self.name = name
def sayHello(self):
print('hello',self.name)
#測試屬性和方法
>>> a.name
'小麥'
>>> a.sayHello()
hello 小麥
#刪除屬性
>>> delattr(a,'name')
>>> a.name
Traceback (most recent call last):
File "<pyshell#47>", line 1, in <module>
a.name
AttributeError: 'A' object has no attribute 'name'
>>> class B: #定義類B
def __call__(self):
print('instances are callable now.')
>>> callable(B) #類B是可調(diào)用對象
True
>>> b = B() #調(diào)用類B
>>> callable(b) #實例b是可調(diào)用對象
True
>>> b() #調(diào)用實例b成功
instances are callable now.
變量操作(2個)
- 返回當(dāng)前作用域內(nèi)的全局變量和其值組成的字典
- 返回當(dāng)前作用域內(nèi)的局部變量和其值組成的字典
>>> globals()
{'__spec__': None, '__package__': None, '__builtins__': <module 'builtins' (built-in)>, '__name__': '__main__', '__doc__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>}
>>> a = 1
>>> globals() #多了一個a
{'__spec__': None, '__package__': None, '__builtins__': <module 'builtins' (built-in)>, 'a': 1, '__name__': '__main__', '__doc__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>}
>>> def f():
print('before define a ')
print(locals()) #作用域內(nèi)無變量
a = 1
print('after define a')
print(locals()) #作用域內(nèi)有一個a變量妓肢,值為1
>>> f
<function f at 0x03D40588>
>>> f()
before define a
{}
after define a
{'a': 1}