1. 程式人生 > >python的內置函數 剖析

python的內置函數 剖析

eva 打印 本地變量 Oz ext -- win locals else

內置方法:

1. abs() #取絕對值;
>>> abs(-11)
11
>>> abs(11)
11

2. all #非0即真,確保所有元素為真才為真;
>>> all([0, -5, 3])
False
>>> all([1, -5, 3])
True

3. any #非0即真,確保一個元素為真就為真;
>>> any([0, -5, 3])
True
>>> any([1, -5, 3])
True
>>> any([0,0])
False

4. ascii() #將內存對象轉變為一個可打印的字符形式
>>> ascii("abcd")
"‘abcd‘"
>>> ascii("abcd111")
"‘abcd111‘"
>>> ascii(1)
‘1‘
>>> ascii([1,2])
‘[1, 2]‘

5. bin() #將十進制數字轉換二進制
>>> bin(8)
‘0b1000‘
>>> bin(19)
‘0b10011‘
>>>

6. bool(): #判斷是否真,空列表等都為假false
>>> bool([])
False
>>> bool([1,2])
True
>>>

7. bytearray() #把字符變成asscii可以更改;
>>> b = bytearray("abdcd", encoding="utf-8")
>>>
>>> print(b[0])
97
>>> print(b[1])
98
>>> b[1]=100
>>> print(b)
bytearray(b‘addcd‘)

a = bytes("abdcd")
>>> a
b‘abdcd

8. chr() #將ascii值轉為對應的字符。
>>> chr(90)
‘Z‘

9. ord() #將字符轉為ascii
>>> ord("a")
97
>>> ord("Z")
90

10. complie() #簡單的編譯反執行。 可以用 exec可以執行字符串源碼;
>>> code = "for i in range(10):print(i)"
>>> code
‘for i in range(10):print(i)‘
>>>
>>> compile(code,"","exec")
<code object <module> at 0x00B540D0, file "", line 1>
>>>
>>> c = compile(code,"","exec")
>>> exec(c)
0
1
2
3
4
5
6
7
8
9
>>>

11. dir() #查看對象的方法:
>>> dir({})
[‘__class__‘, ‘__contains__‘, ‘__delattr__‘, ‘__delitem__‘, ‘__dir__‘, ‘__doc__‘, ‘__eq__‘, ‘__format__‘, ‘__ge__‘, ‘__getattribute__‘, ‘__getitem__‘, ‘__gt__‘, ‘__hash__‘, ‘__init__‘, ‘__init_subclass__‘, ‘__iter__‘, ‘__le__‘, ‘__len__‘, ‘__lt__‘, ‘__ne__‘, ‘__new__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__setattr__‘, ‘__setitem__‘, ‘__sizeof__‘, ‘__str__‘, ‘__subclasshook__‘, ‘clear‘, ‘copy‘, ‘fromkeys‘, ‘get‘, ‘items‘, ‘keys‘, ‘pop‘, ‘popitem‘, ‘setdefault‘, ‘update‘, ‘values‘]
>>> dir([])
[‘__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‘]
>>>


12. divmod() #返回商和余數
>>> divmod(5,1)
(5, 0)
>>> divmod(5,2)
(2, 1)
>>> divmod(5,3)
(1, 2)
>>>

13. enumerate(): #
>>> sersons = ["Spring","Summer","Autron","Wintor"]
>>>
>>> list(enumerate(sersons))
[(0, ‘Spring‘), (1, ‘Summer‘), (2, ‘Autron‘), (3, ‘Wintor‘)]
>>>
>>> list(enumerate(sersons, start=1))
[(1, ‘Spring‘), (2, ‘Summer‘), (3, ‘Autron‘), (4, ‘Wintor‘)]
>>>
>>>
>>> for k,v in enumerate(sersons, start=1):print("%d--%s"% (k, v))
...
1--Spring
2--Summer
3--Autron
4--Wintor
>>>

14. eval() #將字符串轉為數據類型,不能有語句的,有語句的用exec
>>> x = "[1,2,3,4]"
>>> x
‘[1,2,3,4]‘
>>>
>>> x[0]
‘[‘
>>>
>>> y = eval(x)
>>> y
[1, 2, 3, 4]
>>> y[0]
1
>>>

15. exec() # 執行字符串源碼
>>> x = "for i in range(10):print(i)"
>>> x
‘for i in range(10):print(i)‘
>>>
>>>
>>> exec(x)
0
1
2
3
4
5
6
7
8
9
>>>

16. filter(): #按條件進行過濾
>>> x = filter(lambda n:n>5, range(10))
>>> for i in x:print(i)
...
6
7
8
9


將後面的值拿出來給前面處理
>>> x = map(lambda n:n*n, range(10)) #按照範圍的輸出, 相當於:x = [lambda n:n*n for i in range(10)]
>>> for i in x:print(i)
...
0
1
4
9
16
25
36
49
64
81

匿名函數:只能處理3月運算
>>> lambda n:print(n)
<function <lambda> at 0x0368BDB0>
>>>
>>> (lambda n:print(n))(5)
5
>>>
>>> x=lambda n:print(n)
>>> x(5)
5
>>> lambda m:m*2
<function <lambda> at 0x03716198>
>>> y=lambda m:m*2
>>> y(5)
10
>>>
>>> z = lambda n:3 if n<4 else n
>>> z(2)
3
>>> z(5)
5

17. frozenset() #集合凍結,後即不可修改

>>> a=set([12,2,12,12,12,12])
>>> a
{2, 12}
>>> a.add(13)
>>> a
{2, 12, 13}
>>>
>>> b = frozenset(a)
>>> b
frozenset({2, 12, 13})
>>>
>>>
>>> b.add(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: ‘frozenset‘ object has no attribute ‘add‘
>>>


18. globals() #返回整個程序所有的全局變量值:
>>> globals()
{‘__name__‘: ‘__main__‘, ‘__doc__‘: None, ‘__package__‘: None, ‘__loader__‘: <class ‘_frozen_importlib.BuiltinImporter‘>, ‘__spec__‘: None, ‘__annotations__‘: {}, ‘__builtins__‘: <module ‘builtins‘ (built-in)>, ‘Iterable‘: <class ‘collections.abc.Iterable‘>, ‘Iterator‘: <class ‘collections.abc.Iterator‘>, ‘x‘: <map object at 0x00B56030>, ‘a‘: {2, 12, 13}, ‘b‘: frozenset({2, 12, 13}), ‘code‘: ‘for i in range(10):print(i)‘, ‘c‘: <code object <module> at 0x00B54128, file "", line 1>, ‘i‘: 81, ‘sersons‘: [‘Spring‘, ‘Summer‘, ‘Autron‘, ‘Wintor‘], ‘k‘: 4, ‘v‘: ‘Wintor‘, ‘y‘: <function <lambda> at 0x036AB6A8>, ‘z‘: <function <lambda> at 0x03716150>}
>>>

19. hash() # 返回hash值;
>>> hash("1")
-585053941
>>>
>>> hash("qwqw")
1784621666
>>>

19. hex() #抓16進制
>>> hex(100)
‘0x64‘
>>> hex(15)
‘0xf‘
>>>

20. oct() #轉為8進制
>>> oct(10)
‘0o12‘

21. locals() #打印本地變量;
>>> locals()
{‘__name__‘: ‘__main__‘, ‘__doc__‘: None, ‘__package__‘: None, ‘__loader__‘: <class ‘_frozen_importlib.BuiltinImporter‘>, ‘__spec__‘: None, ‘__annotations__‘: {}, ‘__builtins__‘: <module ‘builtins‘ (built-in)>, ‘Iterable‘: <class ‘collections.abc.Iterable‘>, ‘Iterator‘: <class ‘collections.abc.Iterator‘>, ‘x‘: <map object at 0x00B56030>, ‘a‘: {2, 12, 13}, ‘b‘: frozenset({2, 12, 13}), ‘code‘: ‘for i in range(10):print(i)‘, ‘c‘: <code object <module> at 0x00B54128, file "", line 1>, ‘i‘: 81, ‘sersons‘: [‘Spring‘, ‘Summer‘, ‘Autron‘, ‘Wintor‘], ‘k‘: 4, ‘v‘: ‘Wintor‘, ‘y‘: <function <lambda> at 0x036AB6A8>, ‘z‘: <function <lambda> at 0x03716150>}
>>>

21. max(): #返回最大值
>>> max([1,2,3,4,5])
5 23. min(): #返回最小值
>>> min([1,2,3,4,5])
1

24. pow(x,y) #返回多次冪,x的y次方
>>> pow(2,2)
4
>>> pow(2,3)
8

25. range(start,stop,step) 26. repr() #用字符串表示一個對對象:

27. reversed(seq) #反轉

28. round() #浮點數按照規定四舍五入舍棄,
>>> round(1.232442)
1
>>> round(1.232442,2)
1.23
>>> round(1.237442,2)
1.24
>>>

29. id() #取內存id值
>>> id("1")
56589120
>>> id("a")
56501888

30. sorted(iterable[,key][,reverse]) #排序
>>> a = {5:1,9:2,1:3,8:4,3:9}
>>>
>>> sorted(a)
[1, 3, 5, 8, 9]
>>> sorted(a.items())
[(1, 3), (3, 9), (5, 1), (8, 4), (9, 2)]

>>> sorted(a.items(),key=lambda x:x[1])
[(5, 1), (9, 2), (1, 3), (8, 4), (3, 9)]
>>> a.items() #將字典轉化為列表。
dict_items([(5, 1), (9, 2), (1, 3), (8, 4), (3, 9)])
>>>
>>> list(a)
[5, 9, 1, 8, 3]


31. sum(iterable[,start]) #求和,start為sum初始值
>>> sum([1, 3, 5, 8, 9])
26
>>> sum([1, 3, 5, 8, 9],3)
29
>>> sum([1, 3, 5, 8, 9],30)
56

32. tuple(iterable): #轉化為元組
>>> tuple([1, 3, 5, 8, 9])
(1, 3, 5, 8, 9)

34. zip() #中文就是拉鏈的意思,一一對應
>>> a = (1, 3, 5, 8, 9)
>>> b = ("a","b","c","d","e")
>>>
>>> zip(a,b)
<zip object at 0x00B53990>
>>> for n in zip(a,b):
... print(n)
...
(1, ‘a‘)
(3, ‘b‘)
(5, ‘c‘)
(8, ‘d‘)
(9, ‘e‘)
>>>


35. __import__("模塊名") #只知道模塊名時導入模塊就方法:

python的內置函數 剖析