內置函數-max、min、round、sorted、ord、chr、any、all、dir、eval、exec、map、filter
阿新 • • 發佈:2018-11-10
簡單 http 結果 world -s www. [] 安全 pytho
http://www.nnzhp.cn/archives/152
1、max,min,round
1 print(max([3,4.563,3,6,2.5])) #取最大值,可循環參數即可,int類型的,字符串類型不行 2 print(min(9,4,7,1,0)) #取最小值 3 print(round(3.43535345,2)) #取即為小數,四舍五入 4 print(round(1.12345,2))
2、sorted
1 s = ‘235434125636234‘ 2 res = sorted(s) #對字符串排序,默認升序 3 print(list(res)) #需要轉換下類型,打印 4res = reversed(sorted(s))#reversed反轉,降序排序 5 print(list(res)) 6 print(sorted(s,reverse=True)) #降序也可以這樣寫,與上面寫法效果一樣。
#列表有.sort方法
3、ord、chr
1 print(ord(‘a‘))#將字母轉成阿斯克碼裏面的值 2 print(chr(97)) #把數字轉成阿斯克碼表裏面的字母
4、any、all
1 res = any([1,2,3,4,0]) #如果這個循環叠代序列裏面有一個為真的話,就返回true 2 print(res) 3 res = all([1,1,1,0,1])#如果這個循環叠代序列裏面,全部為真,就返回true 4 print(res)
1 print(any((1,2,0))) #返回True 2 print(any((0,0,0))) #全部是0,返回False
5、dir獲取幫助信息
1 import hashlib 2 m = hashlib.md5(‘abc‘.encode()) 3 print(dir(m)) #查看變量m的所有方法
6、eval 執行python代碼,只能執行簡單的,定義數據類型和運算
實例1:
1 # eval#執行python代碼,只能執行簡單的,定義數據類型和運算 2 print(eval(‘1+1‘)) 3 print(eval(‘{"a":"1"}‘))
執行結果:
1 2 2 {‘a‘: ‘1‘}
實例2:
1 f = open(‘a.txt‘).read() #文件裏面的內容是“{‘username‘:‘abc‘,‘password‘:‘123456‘}”,但是讀出來是字符串 2 print(type(f)) 3 print(f) 4 res = eval(f) #轉數據類型 5 print(type(res)) 6 print(res)
執行結果:
1 <class ‘str‘> 2 {‘username‘:‘abc‘,‘password‘:‘123456‘} 3 <class ‘dict‘> 4 {‘username‘: ‘abc‘, ‘password‘: ‘123456‘}
7、exec:執行python代碼的,只要語法對,都能執行,不太安全
1 # 在線寫代碼:http://www.runoob.com/try/runcode.php?filename=HelloWorld&type=python3。這種會對敏感代碼進行控制 2 my_code = ‘‘‘ #前面寫個變量,三引號作用於變量 3 def my(): 4 print(‘運行程序‘) 5 my() 6 ‘‘‘ 7 exec(my_code) #執行python代碼的,這種方式不安全
運行程序
8、map
map是循環幫你調用函數,然後保存函數的返回值,python3中,返回的值放到了一個生成器裏面。需要list強制類型轉換下(能轉成list或元組,集合等可變的類型)。
map後面傳的可以循環就行(字符串、列表等)
實例:
寫一個調用函數:
1 l = [1, 3, 4, 6, 2, 4, 7] 2 l2 = [] #定義一個空list存放補0後的值 3 def bl(i): # 定義一個補0的函數 4 return str(i).zfill(2) 5 for i in l: 6 l2.append(bl(i)) 7 print(l2)
[‘01‘, ‘03‘, ‘04‘, ‘06‘, ‘02‘, ‘04‘, ‘07‘]
上面這個可以用map寫:
1 #另外用map寫,幫你循環調用函數 2 l = [1, 3, 4, 6, 2, 4, 7] 3 l2 = list(map(bl,l)) 4 # l2 = tuple(map(bl,l)) 5 # l2 = set(map(bl,l)) #集合會去重 6 print(l2)
[‘01‘, ‘03‘, ‘04‘, ‘06‘, ‘02‘, ‘04‘, ‘07‘]
9、filter()
也是循環調用函數的,如果函數返回的值是真,那麽就保存這個值.如果返回值假,則過濾掉(過濾你傳過來的值)
實例1:上面的例子用filter過濾:
1 def bl(i): # 定義一個補0的函數 2 return str(i).zfill(2) 3 l = [1, 3, 4, 6, 2, 4, 7] 4 l3 = list(filter(bl,l)) 5 print(l3)
結果:返回的都是真,則全部值保留,list強制類型轉換後,放在list中
[1, 3, 4, 6, 2, 4, 7]
實例2:
1 def bl(i): # 定義一個補0的函數 2 if i >3: 3 return True 4 l = [1, 3, 4, 6, 2, 4, 7] 5 l3 = list(filter(bl,l)) #循環調用函數,過濾掉傳入的list中小於3的值 6 print(l3)
結果:
[4, 6, 4, 7]
內置函數-max、min、round、sorted、ord、chr、any、all、dir、eval、exec、map、filter