1. 程式人生 > >Python__內置函數

Python__內置函數

sin 作用域 key dir range encoding 十進制轉二進制 als 調用

#定義一個函數與變量的定義非常相似,對於有名函數,必須通過變量名訪問
def func(x,y,z = 1):
return x + y + z
#匿名函數:1.沒有名字,2.函數體自帶return
#匿名函數的應用場景,臨時使用
lambda x,y,z = 1:x + y + z
print(lambda x,y,z = 1:x + y + z)
f = lambda x,y,z = 1:x + y + z
print(f)
f(1,2,3)

#內置函數
#1.abs()
print(all([1,2,‘a‘,None]))#表示可叠代對象取出的每一個值的布爾值都為真
print(all([]))#可叠代對象為空的列表,表示為True
print(any([]))#表示為False
print(any([‘ ‘,None,False]))#表示為True
print(any([‘‘,None,False]))#表示為False

#bin,oct,hex
print(bin(10))#十進制轉二進制
print(oct(10))#十進制轉八進制
print(hex(10))#十進制轉十六進制

#bytes
#字符串本身就是unicode
#unicode------->encode------>bytes
print(‘hello‘.encode(‘utf-8‘))
print(bytes(‘hello‘,encoding = ‘utf-8‘))

#callable是否可以被調用
print(callable(bytes))#True
print(callable(abs))#True

#chr,ord
print(chr(65))#A
print(chr(35))#表示的是#
print(ord(‘#‘))#表示的是35

s1 = frozenset({1,2,3,4})#表示的是不可變集合

import sys
sys.path ##path表示來自於sys名稱空間的名字
print(dir(sys))#查看sys有哪些屬性

#divmod
print(divmod(10,3))#結果表示的是除數和商

#enumerate
l = [‘a‘,‘b‘,‘c‘]
res = enumerate(l)
for index,item in res:
print(index,item)

#hash(),表示的是檢驗一段字符串,會得到hash值

#help()查看幫助信息
print(help())#在函數中寫註釋信息,可通過help查看

#id:是python解釋器實現的功能,並不是真實的內存地址

#isinstance
x = 1
print(isinstance(x,int))#判斷x是否是int的一個實例

#pow
print(pow(10,2))#表示的是10**2
print(pow(3,2,2))#表示的是3**2%2

#repr:將對象轉成字符串
print(type(repr(1)))#解釋器內部調用

#reversed
l = [1,‘a‘,2,‘c‘]
print(reversed(l))


#round
print(round(3.567,2))#表示的保留兩位小數

#slice
l = [1,2,3,4,5,6]
print(l[0:4:2])
s = slice(0,4,2)
print(l[s])#可以給多個對象使用

#sorted
l = [1,10,4,3,-1]
print(sorted(l,reverse = True))

#zip:拉鏈(找兩個一一對應的部分)
s = ‘hello‘
l = [1,2,3,4,5]
print(zip(s,l))
res = zip(s,l)#為叠代器
print(list(res))

#__import__
import sys
m_name = input(‘module>>: ‘)
if m_name == ‘sys‘:
m = __import__(m_name)
print(m)
print(m.path)



salaries = {
‘egon‘:3000,
‘alex‘:100000,
‘wupeiqi‘:1000,
‘yuanhao‘:2000
}
# print(list(zip(salaries.values(),salaries.keys())))

# print(max(list(zip(salaries.values(),salaries.keys()))))

# print(max(salaries,key = lambda name:salaries[name]))


##filter,map,reduce
names = [‘alex‘,‘wupeiqi‘,‘yuanhao‘,‘egon‘]
# res = map(lambda x:x + ‘_SB‘,names)
# print(list(res))

#從functools中導入reduce模塊
from functools import reduce
# print(reduce(lambda x,y:x + y,range(101)))


def my_map(seq):
for item in seq:
item = item + ‘_SB‘
yield item
res1 = my_map(names)
# print(next(res1))

def my_map(func,seq):
for item in seq:
yield func(item)
# res1 = my_map(lambda x:x + ‘_SB‘,names)
# print(next(res1))

##filter函數
names = [‘alex_SB‘,‘wupeiqi‘,‘yuanhao‘,‘egon‘]
# print(list(filter(lambda name:name.endswith(‘SB‘),names)))

##eval與exec
# cmd = ‘print(x)‘
# x = 1
# eval(cmd)
# eval(cmd,{},{})#第一個大括號表示的是全局作用域,第二個大括號表示的是局部作用域
# eval(cmd,{‘x‘:0},{‘y‘:10000})

s = ‘for i in range(10):print(i)‘
code = compile(s,‘‘,‘exec‘)
exec(code)

Python__內置函數