天天看點

python内置函數

 内置函數詳解:https://docs.python.org/3/library/functions.html?highlight=built#ascii

abs()  # 取絕對值
dict() # 把資料轉為字典
help() # 幫助
min()  # 找出最小值
max()  # 找出最大值
setattr()  # 設定屬性值
bool() # 判斷True or False(bool(0)、bool(Flase)、bool([]))
all()  # 可循環的資料集合每個元素bool()均為True;或者空清單也是True
any()  # 任意一個值是True即傳回True
dir()  # 列印目前程式裡的所有變量
hex()  # 轉換為16進制數
slice()  # 提前定義切片規則
divmod()  # 傳入兩個變量a、b,得到a//b結果和餘數a%b
sorted()  # 清單排序sorted(li)等同于li.sort()  用法:sorted(iterable, key)

ascii(2)  # 隻能傳回ascii碼
enumerate([3,2,13,4])  # 傳回清單的索引
input('dasd')
oct(10)  # 轉八進制
staticmethod() # 
bin(10)  # 轉二進制

open() # 檔案打開
str()  # 轉字元串
isinstance()
ord('a')  # 傳回97,ascii碼中'a'位置
chr(97)   # 傳回'a',輸入97位置傳回ascii碼對應字元
sum([1,4,5,-1,3,0])   # 計算清單求和

pow(100,2) # 傳回x的y次方,10000
callable()   # 檢視函數是否可以調用,還可用于判斷變量是否是函數
format()

vars()  # 列印變量名和對應的值
locals()  # 列印函數的局部變量(一般在函數内運作)
globals() # 列印全局變量

repr()  # 顯示形式變為字元串
compile() # 編譯代碼
complex() # 将一個數變為複數
'''
>>> complex(3,5)
(3,5j)
'''

round(1.2344434,2)  # 指定保留幾位小數  輸出1.23
# delattr, hasattr, getattr, setattr  # 面向對象中應用
hash()   # 把一個字元串變為一個數字
memoryview() # 大資料複制時記憶體映射
set()  # 把一個清單變為集合
'''
>>> set([12,5,1,7,9])
{1, 5, 7, 9, 12}
'''      

幾個刁鑽古怪的内置方法用法提醒

1、compile()編譯字元串為位元組代碼

f = open("print.py")
data =compile(f.read(),'','exec')  # 參數:source(字元串對象), filename(代碼檔案名), mode(編譯代碼種類exec\eval\single)
exec(data)

>>> str = "3 * 4 + 5"
>>> a = compile(str,'','eval')
>>> eval(a)
17
      

2、items()字典轉化數組

>>> d = {}
>>> for i in range(10):
...        d[i] = i - 50
...
>>> print(d)
{0: -50, 1: -49, 2: -48, 3: -47, 4: -46, 5: -45, 6: -44, 7: -43, 8: -42, 9: -41}
>>> d.items()
dict_items([(0, -50), (1, -49), (2, -48), (3, -47), (4, -46), (5, -45), (6, -44), (7, -43), (8, -42), (9, -41)])
>>> sorted(d.items())
[(0, -50), (1, -49), (2, -48), (3, -47), (4, -46), (5, -45), (6, -44), (7, -43), (8, -42), (9, -41)]
>>> sorted(d.items(), key = lambda x:x[1])
[(0, -50), (1, -49), (2, -48), (3, -47), (4, -46), (5, -45), (6, -44), (7, -43), (8, -42), (9, -41)]
>>> sorted(d.items(), key = lambda x:x[1], reverse=True)
[(9, -41), (8, -42), (7, -43), (6, -44), (5, -45), (4, -46), (3, -47), (2, -48), (1, -49), (0, -50)]
      

3、字元串轉代碼

# eval()  # 字元串轉代碼(隻能處理單行代碼)(可以拿到傳回值)
f = "1+3/2"
eval(f)
# 輸出結果:2.5
eval('print("hello world")')
# 輸出結果:hello world

# exec() # 字元串轉代碼(可以解析多行代碼)(不能拿到傳回值)
code = "\nif 3>5:\n print('3 bigger than 5')\nelse:\n print('dddd')\n\n"
exec(code)
# 輸出結果:dddd

# eval和exec()傳回值驗證
code = '''
def foo():
    print('run foo')
    return 1234
foo()

res = eval("1+3+3")
res2 = exec("1+3+3")
res3 = exec(code)
print('res',res,res2,res3)
# 輸出結果:res 7 None None
      

4、字元串轉bytearray

# bytearray() 将字元串轉為bytearray,完成修改後,decode()後,可在原記憶體位址修改字元串

>>> s = 'abcd路飛'
>>> s
'abcd路飛'
>>> s = s.encode('utf-8')
>>> s
b'abcd\xe8\xb7\xaf\xe9\xa3\x9e'
>>> s = bytearray(s)
>>> s
bytearray(b'abcd\xe8\xb7\xaf\xe9\xa3\x9e')
>>> s[4]
232
>>> s[4]=233
>>> s
bytearray(b'abcd\xe9\xb7\xaf\xe9\xa3\x9e')
>>> s.decode()
'abcd鷯飛'
>>> id(s)   # 修改内部元素,s指向的記憶體位址并不會改變
4352883880
      

 5、map()對序列做映射

map(lambda x:x*x , [1,2,3,4,5])    # 根據提供的函數對指定序列做映射

>>> list(map(lambda x:x*x , [1,2,3,4,5]))
[1, 4, 9, 16, 25]

>>>def square(x) :            # 計算平方數
...     return x ** 2
... 
>>> map(square, [1,2,3,4,5])   # 計算清單各個元素的平方
[1, 4, 9, 16, 25]
>>> map(lambda x: x ** 2, [1, 2, 3, 4, 5])  # 使用 lambda 匿名函數
[1, 4, 9, 16, 25]
 
# 提供了兩個清單,對相同位置的清單資料進行相加
>>> map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
[3, 7, 11, 15, 19]
      

6、filter()條件過濾

filter() # 将符合條件的值過濾出來
# filter(function, iterable)
>>> list(filter(lambda x: x>3, [1,2,3,4,5]))
[4, 5]

import math
def is_sqr(x):
    return math.sqrt(x) % 1 == 0
 
newlist = filter(is_sqr, range(1, 101))
print(newlist)
"""
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
"""
      

7、frozenset()不可變集合

>>> s = {12,3,4,4}
>>> s.discard(3)  # 集合删除元素,沒有也不會報錯
>>> s
{12,4}
>>> s = frozenset(s)
>>> s.   # 已經沒有discard方法可以調用
      

8、zip()兩個數組組成元組

zip()  # 可将兩個數組一一對應組成元祖

>>> a = [1,2,3,45,6]
>>> b = ['a','b','c']
>>> zip(a)
<zip object at 0x1034fe408>
>>> list(zip(a,b))
[(1, 'a'), (2, 'b'), (3, 'c')]
      

9、print()帶參數的列印

>>> s = 'hey, my name is alex\n, from shandong'
>>> print('haifeng','gangsf',sep='<-')
haifeng<-gangsf

msg = "回到最初的起點"
f = open("print_tofile","w")
print(msg,"記憶裡青澀的臉",sep="|",end="",file=f)
print(msg,"已經不忍直視了",sep="|",end="",file=f)
"""
生成print_tofile檔案:回到最初的起點|記憶裡青澀的臉回到最初的起點|已經不忍直視了
"""
      

10、slice()切片

slice()  # 實作切片對象,主要用在切片操作函數裡的參數傳遞
# 例子:slice('start', 'stop', 'step')  # 起始位置、結束位置、間距

a = range(20)
pattern = slice(3, 8, 2) # 3到8,間隔兩個數
for i in a[pattern]:  # 等于a[3:8:2]
    print(i)      

11、reduce()對參數序列中元素進行累積

  reduce() 函數将一個資料集合(連結清單,元組等)中的所有資料進行下列操作:用傳給 reduce 中的函數 function(有兩個參數)先對集合中的第 1、2 個元素進行操作,得到的結果再與第三個資料用 function 函數運算,最後得到一個結果。

reduce() 函數文法:
reduce(function, iterable[, initializer])

參數
    function -- 函數,有兩個參數
    iterable -- 可疊代對象
    initializer -- 可選,初始參數
      

   傳回值:函數計算結果

>>>def add(x, y) :            # 兩數相加
...     return x + y
... 
>>> reduce(add, [1,2,3,4,5])   # 計算清單和:1+2+3+4+5
15
>>> reduce(lambda x, y: x+y, [1,2,3,4,5])  # 使用 lambda 匿名函數
15