基礎小函式、字串函式、序列函式
序列、元組、串列小函式
max() 求最大值(串列、元組、序列)
min() 求最小值
len() 求長度
>>> a = [1,2,3,4] >>> max(a) 4 >>> min(a) 1 >>> len(a) 4 >>>
運算小函式
divmod() 求運算模,回傳一個元組,第一個引數是商,第二個是余數
pow(x,y) 指數運算,x的y次方
pow(x,y,z) x的y次方,在與z取模
round() 浮點數
>>> a = 3 >>> b = 4 >>> divmod(a,b) (0, 3) >>> divmod(b,a) (1, 1) >>> pow(a,b) 81 >>> pow(a,b,8) 1 >>> >>> a/b 0.75 >>> round(a/b) 1 >>> round(a/b,2) 0.75 >>> round(a/b,4) 0.75 >>>
其它小函式
callable() 測驗函式是否可被呼叫
isinstance(l,list) 測驗l是否是一個list
>>> def f(x): pass >>> callable(fc) Traceback (most recent call last): File "<pyshell#3>", line 1, in <module> callable(fc) NameError: name 'fc' is not defined >>> callable(f) True >>> >>> l = [1,2,3,4] >>> t = (2,3,4,5) >>> s = 'hello' >>> isinstance(l,list) True >>> isinstance(t,tuple) True >>> isinstance(s,str) True >>> isinstance(l,str) False
字串函式
str.capitalize() 首字母大寫
str.replace('x','y',count) 字串替換 count 替換幾次
str.split(“”,sep) 將字串轉換為串列,用“”切割,sep切割幾次
>>> str1 = 'hello world , today is very good day' >>> str1.capitalize() 'Hello world , today is very good day' >>> str1 'hello world , today is very good day' >>> str1.replace('o','9',1) 'hell9 world , today is very good day' >>> str1.replace('o','9',3) 'hell9 w9rld , t9day is very good day' >>> str1.replace('o','9') 'hell9 w9rld , t9day is very g99d day' >>> >>> ip = '192.168.1.254' >>> ip.split(".") ['192', '168', '1', '254'] >>> ip.split(".",1) ['192', '168.1.254'] >>>
序列函式
filter() 過濾函式
filter(f,l) 將l串列中的值傳給函式f進行判斷,保留滿足要求的數值 函式return True
zip() 將兩個串列的值進行對應,以元組存放在串列中,以最短的為組合數
map(None,a,b) 將串列a、b的值對應起來傳給None函式,None可以作為函式
fc(x,y)
reduce(fc,list) 將串列list的值依次傳輸給函式fc
>>> def f(x): if x>5: return True >>> l = [1,2,3,5,6,2,3,6,7,8] >>> filter(f,l) <filter object at 0x00000220AC4C95E0> >>> list(filter(f,l)) [6, 6, 7, 8] >>> >>> name = ['zhang','li','wang','zhou'] >>> age = [22,21,23,24] >>> list(zip(name,age)) [('zhang', 22), ('li', 21), ('wang', 23), ('zhou', 24)] >>> city = ['beijing','shanxi','xinjiang'] >>> list(zip(name,age,city)) [('zhang', 22, 'beijing'), ('li', 21, 'shanxi'), ('wang', 23, 'xinjiang')] >>> >>> def f(name,age): return name,age >>> list(map(f,name,age)) [('zhang', 22), ('li', 21), ('wang', 23), ('zhou', 24)] >>> >>> def f(x,y): return x+y >>> a = [1,2,3,4] >>> b = [1,2,3,4] >>> list(map(f,a,b)) [2, 4, 6, 8] >>> >>> >>> l = range(100) >>> reduce(f,l) Traceback (most recent call last): File "<pyshell#29>", line 1, in <module> reduce(f,l) NameError: name 'reduce' is not defined >>> >>> from functools import reduce >>> reduce(f,l) 4950 >>> l = range(101) >>> reduce(f,l) 5050 >>> >>>
使用reduce時需要匯入相應的模塊,
reduce用來計算階乘很方便,根據reduce,可以寫成一行代碼來,
>>> n = 101 >>> range(n) range(0, 101) >>> reduce(lambda x,y:x+y , l) 5050 >>>
+修改為*,就是求n的階乘了,不對n-1的階乘,
小例子動手寫一下,印象更深刻,
讀書和健身總有一個在路上
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/153376.html
標籤:Python
上一篇:LeetCode 46. 全排列
下一篇:Python學習筆記:模塊學習
