1. 程式人生 > >學習Pytbon第十天 函式2 內建方法和匿名函式

學習Pytbon第十天 函式2 內建方法和匿名函式

print( all([1,-5,3]) )#如果可迭代物件裡所有元素都為真則返回真。0不為真
print( any([1,2]) )#如果資料裡面任意一個數據為真返回則為真
a= ascii([1,2,"天氣"])#把一個記憶體資料物件轉成字串表現形式打印出來
print(type(a),[a])
bin #把一個數字轉二進位制

a = bytes("abcde",encoding="utf-8")#位元組陣列
b = bytearray("abcde",encoding="utf-8")#可修改的二進位制位元組格式
print( b[1] )
b[1]= 50
print(b)
print(a.capitalize(),a)#判斷是否可以呼叫,能夠加括號的就可以呼叫

def sayhi():pass
print( callable(sayhi) )
chr(98)#數字對應字母
ord(a)#字母對應數字
#斐波那契數列
code = '''
def fib(max): #10
n, a, b = 0, 0, 1
while n < max: #n<10
#print(b)
yield b
a, b = b, a + b
#a = b a =1, b=2, a=b , a=2,
# b = a +b b = 2+2 = 4
n = n + 1
return '---done---'


#f= fib(10)
g = fib(6)
while True:
try:
x = next(g)
print('g:', x)
except StopIteration as e:
print('Generator return value:', e.value)
break

'''

a={}
print(dir(a))#dir可以檢視有哪些方法
print(divmod(5,1))#divmod求商和餘數

exec(code)#可實現動態匯入功能,遠端傳遞程式碼

py_obj = compile(code,"err.log","exec")

eval(py_obj)#功能同上
x=1
print(eval('x+1'))#eval把字串變字典返回2

#匿名函式
(lambda n:print(n))(5) #lambda匿名函式
calc=lambda n:print(n)
calc(7)
calc = lambda n:3 if n<4 else n
print(calc(1))

res = filter(lambda n:n>5,range(10))#filter過濾功能
for i in res:
print(i)
res = map(lambda n:n*2,range(10))#列表生成式[i*2 for i in rang(10)]
for i in res:
print(i)
# res = [ lambda i:i*2 for i in range(10)]#同上
import functools #reduce被引入標準庫內
res = functools.reduce( lambda x,y:x+y,range(10 ))#累加
res2 = functools.reduce( lambda x,y:x*y,range(1,10 ))
# print(res )
# print(res2 )
# #
a = frozenset([1,4,333,212,33,33,12,4])#凍結的,不可比變列表
print(globals())#字典,判斷一個變數是否存在,整個程式的變數的變數名是k變數對應值是valley

def test():
local_var =333
print(locals())
print(globals())
test()
print(globals())
print(globals().get('local_var'))
max#返回最大值

a = {6:2,8:0,1:4,-5:6,99:11,4:22}

print( sorted(a.items()) )#按照Key進行排序變成列表
print( sorted(a.items(),key=lambda x:x[1]) )#按照vell排序
# print(a )
oct#轉八進位制
a = [1,2,3,4,5,6]
b = ['a','b','c','d']

for i in zip(a,b):#拉鍊
print(i)
import decorator
__import__('decorator')
reversed(seq)#反轉
round()#保留兩位小數
slice()#切片