python內置函數的簡單使用和介紹

"""
內置函數的簡單使用和介紹
參考連接:https://docs.python.org/3/library/functions.html


"""
1.
abs() # 絕對值
"""
n = abs(-10)
print (n)
# 10



"""
2.
all() # 全爲真,輸出Ture , 則輸出Flase
any() # 只要有真,輸出Ture,則輸出Flase

0,None,"",[],(),{} # False
"""
n1 = all([1,2,3,[],None])
print (n1)
# False
n2 = any([1,0,"",[]])
print (n2)
# True

  


"""
3.
ascii()
自動執行對象的__repr__方法
"""
class Foo:
    def __repr__(self):
        return "444"
n = ascii(Foo())
print (n)
# 444

  



"""
4.
bin() # 將十進制轉爲二進制 0b 表示二進制
oct() # 將十進制轉爲八進制 0o 表示八進制
hex() # 將十進制轉爲十六進制 0x 表示十六進制
"""
print (bin(5))
print (oct(9))
print (hex(27))
# 0b101
# 0o11
# 0x1b

  



"""
5.
bool() 布爾值
0,None,"",[],(),{} 表示False
"""


"""
6.
bytes()
utf8 編碼,一個漢字3個字節
gbk 編碼,一個漢字2個字節
一個字節 == 8位

str()
字節轉化爲字符串
"""
# 將字符串轉換爲字節類型,系統中的表現形式爲16進制
# bytes(字符串,編碼格式)
s = "中國"
n3 = bytes(s,encoding="utf-8")
print (n3)
# b'\xe4\xb8\xad\xe5\x9b\xbd'
n4 = bytes(s,encoding="gbk")
print (n4)
# b'\xd6\xd0\xb9\xfa'

n5 = str(b'\xd6\xd0\xb9\xfa',encoding="gbk")
print (n5)
# 中國
n6 = str(b'\xe4\xb8\xad\xe5\x9b\xbd',encoding="utf-8")
print (n6)
# 中國

  




"""
7.
callable()
檢測傳遞的值是否能夠調用
"""
def f1():
    pass
f1()
f2 = 123
print (callable(f1))
# True
print (callable(f2))
# False

  



"""
8.
chr()
ord()
輸出 ASCII的對應關係,chr()輸出十進制位置的字符,ord()輸出字符在ASCii表的位置
"""
print (chr(65))
# A
print (ord("A"))
# 65

# 實例1:生成6位數隨機密碼,純字母
# import random
# li = []
# for i in range(6):
#     temp = chr(random.randrange(65,91))
#     li.append(temp)
# print (li)
# result = "".join(li)
# print (result)

# 實例2:生成8位數隨機密碼,帶數字,字母
import random
li = []
for i in range(8):
    r = random.randrange(0,6)   # 讓生成數字的位置隨機
    if r == 2 or r == 5:
        num = random.randrange(0,10)
        li.append(str(num))
    else:
        temp = random.randrange(65,91)
        c = chr(temp)
        li.append(c)
result = "".join(li)
print (result)
# 3E4JVHF8

  



"""
9.
compile() # 編譯,將字符串編譯成python代碼
eval() # 執行表達式,而且獲取結果
exec() # 執行python代碼

注:eval有返回值,exec沒返回值
python hello.py 過程:
1.讀取文件內容open,str 到內存
2.python,把字符串 -> 編譯 -> 特殊代碼
3.執行代碼
"""
s = "print('hello,python~')"
r = compile(s,"<string>","exec")
exec (r)
# hello,python~
ss = "8*8+5"
print (eval(ss))
# 69

  


"""
10.
dir()
help()
快速獲取模塊,對象提供的功能
"""
print (dir(tuple))
print (help(tuple))

  




"""
11.
divmod()
獲得商和餘數
"""
n1,n2 = divmod(96,10)
print (n1,n2)
# 9 6

 



"""
12.
isinstance()
用於判斷,對象是不是某個類的實例
"""
s1 = "hello"
r = isinstance(s1,str)
print (r)
# True
r1 = isinstance(s1,list)
print (r1)
# Flase

  


"""
13.
filter() # 函數返回值爲Ture,將元素添加結果中
# filter 循環第二個參數,讓每一個循環元素執行函數,若是函數返回值爲Ture,表示函數合法
map() # 將函數返回值添加結果中
# (函數,可迭代的對象(能夠for循環))
"""
# 示例1
def f1(args):
    result = []
    for item in args:
        if item > 22:
            result.append(item)
    return result
li = [11,22,33,44,55,66,77,88]
ret = f1(li)
print (ret)
# [33, 44, 55, 66, 77, 88]

# 優化示例1
def f2(a):
    if a > 22:
        return True
ls1 = [11,22,33,44,55,66,77]
res1 = filter(f2,ls1)
print(list(res1))
# [33, 44, 55, 66, 77]

# 知識擴展,lambda 函數
res2 = filter(lambda x:x > 22,ls1)
print (res2) # 返回一個filter object
# <filter object at 0x000000E275771748>
print (list(res2))
# [33, 44, 55, 66, 77]

# 示例2
def f1(args):
    result = []
    for i in args:
        result.append(i + 100)
    return result
lst1 = [11,22,33,44,55,66]
rest = f1(lst1)
print (list(rest))
# [111, 122, 133, 144, 155, 166]

# 優化示例2,,,map函數
def f2(a):
    return a + 100
lst2 = [11,22,33,44,55,66]
result1 = map(f2,lst2)
print (list(result1))
# [111, 122, 133, 144, 155, 166]

# 優化示例2,map函數+lambda函數
lst3 = [11,22,33,44,55,66]
result2 = map(lambda a:a+100,lst3)
print (list(result2))
# [111, 122, 133, 144, 155, 166]



"""
14.
globals() # 全部的全局變量
locals() # 全部的局部變量
"""
name = "python"
def show():
    a = 123
    b = 456
    print (locals())
    print (globals())
show()
# {'a': 123, 'b': 456}
# {'result': '3VZ8B1V0', 'res1': <filter object at 0x000000ECFE24B5C0>, 'lst3': [11, 22, 33, 44, 55, 66], '__package__': None, 'f2': <function f2 at 0x000000ECFFCB9268>, 'ss': '8*8+5', 'n2': 6, 'n3': b'\xe4\xb8\xad\xe5\x9b\xbd', 'temp': 86, 's1': 'hello', 'n': '444', 'name': 'python', 'i': 7, 'rest': [111, 122, 133, 144, 155, 166], '__spec__': None, 'lst1': [11, 22, 33, 44, 55, 66], 'r1': False, 'num': 0, '__builtins__': <module 'builtins' (built-in)>, 'n6': '中國', 'random': <module 'random' from 'C:\\Users\\xieshengsen\\AppData\\Local\\Programs\\Python\\Python35\\lib\\random.py'>, 's': "print('hello,python~')", '__file__': 'D:/PycharmProjects/高級自動化/模塊學習/內置函數_v1.py', 'f1': <function f1 at 0x000000ECFFCBF510>, 'result2': <map object at 0x000000ECFE25EC88>, 'show': <function show at 0x000000ECFFCBF2F0>, 'ret': [33, 44, 55, 66, 77, 88], '__cached__': None, 'li': [11, 22, 33, 44, 55, 66, 77, 88], '__doc__': '\n內置函數的簡單使用和介紹\n參考連接:https://docs.python.org/3/library/functions.html\n', 'c': 'V', 'result1': <map object at 0x000000ECFE260D30>, 'Foo': <class '__main__.Foo'>, 'n1': 9, 'n5': '中國', 'r': True, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x000000ECFDFEA898>, 'ls1': [11, 22, 33, 44, 55, 66, 77], 'lst2': [11, 22, 33, 44, 55, 66], 'res2': <filter object at 0x000000ECFE24B4A8>, 'n4': b'\xd6\xd0\xb9\xfa', '__name__': '__main__'}


"""
15.
hash()
生成一個hash值(字符串)
"""
has = "python"
print (hash(has))
# 839578881833832098

  



"""
16.
len()
輸出對象的長度
"""
print(len("python"))
# 6
print (len("長城")) # python3,  python2 輸出長度爲6 (python3按字符,python2按字節)
# 2

  



"""
17.
max() # 最大值
min() # 最小值
sun() # 求和
"""
lit = [11,22,33,44,55]
print (max(lit))
print (min(lit))
print (sum(lit))
# 55
# 11
# 165

  



"""
18.
pow()
求指數
"""
print(pow(2,10))
# 1024

  



"""
19.
reverse()
反轉
"""
lit1 = [11,22,33,44,55,66]
print (list(reversed(lit1)))
# [66, 55, 44, 33, 22, 11]

  



"""
20.
round()
四捨五入求值
"""
print (round(1.4))
print (round(1.8))
# 1
# 2

  



"""
21.
sorted()
排序 等同於列表的sort
"""
lit2 = [12,32,1,3,4,34,11,5]
print (list(sorted(lit2)))
# [1, 3, 4, 5, 11, 12, 32, 34]
lit2.sort()
print (lit2)
# [1, 3, 4, 5, 11, 12, 32, 34]



"""
22.
zip()
"""
l1 = ["hello",11,22,33]
l2 = ["world",44,55,66]
l3 = ["python",77,88,99]
l4 = zip(l1,l2,l3)
# print (list(l4))
# # [('hello', 'world', 'python'), (11, 44, 77), (22, 55, 88), (33, 66, 99)]
temp1 = list(l4)[0]
print (temp1[0])
ret1 = " ".join(temp1)
print (ret1)
# hello world python
相關文章
相關標籤/搜索