天天看點

Python程式設計:Built-in Functions内建函數小結

Built-in Functions(68個)

1、數學方法

abs() sum() pow() min() max() divmod() round()

2、進制轉換

bin() oct() hex()

3、簡單資料類型

- 整數:int()

- 浮點數:float()

- 字元\字元串:str() repr() ascii() ord() chr() format()

- 位元組:bytes() bytearray()

- 布爾:bool()

- 複數:complex()

4、資料結構

- 清單:list() slice() range()

- 元組:tuple()

- 字典:dict() hash()

- 集合:set() frozenset()

- 方法:len() zip() all() any() iter() filter() next() sorted() reversed() enumerate() map() memoryview()

5、面向對象

setattr() getattr() delattr() hasattr()

super() property()

staticmethod() classmethod()

isinstance() issubclass()

6、系統方法

dir() help() id() object() type()

input() open() print()

eval() exec() compile()

vars() locals() globals()

callable() __import__()

參考:

https://docs.python.org/3.5/library/functions.html

print(abs(-1))  # 絕對值  1
print(divmod(5, 2))  # 取商和餘數 (2, 1)

# 四舍五入
print(round(1.4)) # 1
print(round(1.5)) # 2
print(round(1.6)) # 2

# 次方,相當于x**y
print(pow(2, 8))  # 256

print(bin(2))  # 轉為二進制  0b10
print(oct(12))  # 轉8進制 0o14
print(hex(20))  # 轉16進制  0x14

print(bool(1))  # 轉為布爾值  True

# 轉為int
s = "12"
i = int(s)
print(type(s), type(i))  # <class 'str'> <class 'int'>

# 轉字元串
i = 12345
s =str(i)
print(type(i), type(s))   # <class 'int'> <class 'str'>

print([ascii([1,2,3])])  # 轉為字元串  ['[1, 2, 3]']

# 轉為可列印對象representation 表現
s = 123456
r =repr(s)
print(type(s), type(r))  # <class 'int'> <class 'str'>

# ascii碼
print(chr(100))  # d
print(ord("a"))  # 97

print(bytes("我是中國人", encoding="utf-8"))
# b'\xe6\x88\x91\xe6\x98\xaf\xe4\xb8\xad\xe5\x9b\xbd\xe4\xba\xba'

b = bytearray("abc", encoding="utf-8")  # 轉為位元組數組
print(b)  # bytearray(b'abc')
print(b[0])  # 97
b[0] = 100
print(b)  # bytearray(b'dbc')

# 建立字典對象
d1 = {}
d2 = dict()
d3 = dict(name = "Tom", age = 23)
print(d1)  # {}
print(d2)  # {}
print(d3)  # {'age': 23, 'name': 'Tom'}

# 擷取散列值
res = hash(1)
print(res)  # 1

res = hash("Tom")  # -1433634475463391166
print(res)

# 不可變集合
st = frozenset([1,2,3,4])
print(type(st))  # <class 'frozenset'>

# 生成清單
lst1 = []
lst2 = list()
lst3 = list((1,2,3))
print(lst1)  # []
print(lst2)  # []
print(lst3)  # [1, 2, 3]

# 計算長度
print(len([1,2,3]))  # 3

# 最大最小值
lst = [1,3,4,5,8,6,9]
print(max(lst))  # 9
print(min(lst))  # 1

# 求和
lst = [i for i in range(5)]
print(sum(lst))  # 10

# 切片
lst = [x for x in range(10)]
s = slice(2,5)
print(lst[s])  # [2, 3, 4]

# 枚舉
for index, value in enumerate(range(1,5)):
    print(index, value)
"""
0 1
1 2
2 3
3 4
"""

print(all([1,2,3]))  # 所有都是真的  True
print(all([1,2,0]))  # False
print(any([1,2,1]))  # 至少存在一個真的  True
print(any([0]))  # False

# 元組
t1 = ()
t2 = (1,)
t3 = tuple()
print(type(t1))  # <class 'tuple'>
print(type(t2))  # <class 'tuple'>
print(type(t3))  # <class 'tuple'>

# 反轉
lst = [1, 2, 3]
print(reversed(lst))  # <list_reverseiterator object at 0x0000000003A54A90>

# lambda 與 三元運算符
lamb = lambda x : 3 if x < 5 else x
print(lamb(5))  # 5

# 過濾
res = filter(lambda x: x>5, range(10))
for i in res:
    print(i,end=" ")  # 6 7 8 9
print()

# 映射
res = map(lambda x: x*x, range(10))
for i in res:
    print(i, end=" ")  # 0 1 4 9 16 25 36 49 64 81
print()
"""
等價于:
res = [lambda x: x*x for x in range(10)]
res = [x*x for x in range(10)]
"""

# 濃縮
import functools  # py3
res = functools.reduce(lambda x, y: x + y, range(10))
print(res)  # 45

# 排序
dct ={"0": 99, "1": 98, "6": 11, "5": 45}
print(dct)  # {'6': 11, '0': 99, '1': 98, '5': 45}
print(sorted(dct))  # ['0', '1', '5', '6']
print(sorted(dct.items()))
# [('0', 99), ('1', 98), ('5', 45), ('6', 11)]
print(sorted(dct.items(), key=lambda x: x[1]))
# [('6', 11), ('5', 45), ('1', 98), ('0', 99)]

# 拉鍊,這個叫法很形象
a = [1, 2, 3, 4, 5]
b = ["a", "b", "c", "d", "e"]
z = zip(a, b)
print(z)  # <zip object at 0x0000000003FBE1C8>
print([i for i in z])
# [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')]

# 轉為疊代器
lst = [1, 2, 3]
ilst = iter(lst)
print(type(lst),type(ilst))  # <class 'list'> <class 'list_iterator'>

# 相當于生成器的__next()__ 方法
lst = range(5)
print(type(ilst))  # <class 'range'>
ilst = iter(lst)
print(type(ilst))  # <class 'range_iterator'>
print(next(ilst))  # 0
print(next(ilst))  # 1

# 判斷是否為某個類的執行個體
d ={}
print(isinstance(d, dict))  # True

# 導入包  動态加載類和函數
__import__("iterator_test")
print()

print(dir(d1))  # 檢視方法
"""
['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__',
 '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', 
 '__getitem__', '__gt__', '__hash__', '__init__', '__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']
"""

print(help(divmod))  # 檢視幫助
"""
Help on built-in function divmod in module builtins:

divmod(...)
    divmod(x, y) -> (div, mod)

    Return the tuple ((x-x%y)/y, x%y).  Invariant: div*y + mod == x.
"""

# 對象id
a = 1
print(id(a))  # 1430299072

# 列印局部變量
def foo():
    a = 1
    print(vars())  # {'a': 1}
foo()

# 列印局部變量
def foo():
    a = 1
    print(locals())  # {'a': 1}
foo()

print(globals())  # 列印目前檔案的所有全局變量,key-value形式傳回
"""
{'code': '\nfor i in range(5):\n    print(i, end=" ")\n',
 '__cached__': None, 'value': 4, 'index': 3, 'd1': {}, 
 'b': bytearray(b'dbc'), 'lamb': <function <lambda> at 0x00000000024E8730>, 
 '__package__': None, 'st': frozenset({1, 2, 3, 4}),
 ...
"""

code = """
for i in range(5):
    print(i, end=" ")
"""
exec(code)  # 運作代碼  0 1 2 3 4
x = 1
print("eval:", eval("x+1"))  # eval: 2

def sayHello():pass
print(callable(sayHello))  # True