第十節 內建函式
help函式可以用來檢視函式的用法
help(range)
#輸出結果
Help on built-in function range in module __builtin__:
range(...)
range(stop) -> list of integers
range(start, stop[, step]) -> list of integers
Return a list containing an arithmetic progression of integers.
range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.
When step is given, it specifies the increment (or decrement).
For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!
These are exactly the valid indices for a list of 4 elements.
常用函式
abs(number)
: 絕對值max(iterable[, key=func])
: 最大值min(iterable[, key=func])
: 最小值len(collection)
: 取得一個序列或集合的長度divmod(x, y)
: 求兩個數的商和模,返回一個元組(x//y, x%y)pow(x, y[, z])
: 求一個數的冪運算round(number[, ndigits])
: 對一個數進行指定精度的四捨五入callable(object)
: 判斷一個物件是否可呼叫isinstance(object, class-or-type-or-tuple)
:判斷物件是否為某個類的例項cmp(x, y)
: 比較兩個數或字串大小range(start [,stop, step])
: 返回一個範圍陣列,如range(3), 返回[0,1,2]xrange(start [,stop, step])
: 作用與range相同,但是返回一個xrange生成器,當生成範圍較大的陣列時,用它效能較高
型別轉換函式
type()
type(object) -> the object's type type(name, bases, dict) -> a new type
int()
int(x=0) -> int or long int(x, base=10) -> int or long
long()
long(x=0) -> long long(x, base=10) -> long
float()
float(x) -> floating point number
complex()
complex(real[, imag]) -> complex number
str()
str(object='') -> string
list()
list() -> new empty list list(iterable) -> new list initialized from iterable's items
tuple()
tuple() -> empty tuple tuple(iterable) -> tuple initialized from iterable's items
hex()
hex(number) -> string
oct()
oct(number) -> string
chr()
chr(i) -> character
ord()
ord(c) -> integer
string函式
str.capitalize()
>>> s = "hello" >>> s.capitalize() 'Hello'
str.replace()
>>> s = "hello" >>> s.replace('h', 'H') 'Hello'
str.split()
>>> ip = "192.168.1.123" >>> ip.split('.') ['192', '168', '1', '123']
序列處理函式
len()
>>>l = range(10) >>> len(l) 10
max()
>>>l = range(10) >>> max(l) 9
min()
>>>l = range(10) >>> min(l) 0
filter()
>>>l = range(10) >>> filter(lambda x: x>5, l) [6, 7, 8, 9]
zip()
>>> name=['bob','jack','mike'] >>> age=[20,21,22] >>> tel=[131,132] >>> zip(name, age) [('bob', 20), ('jack', 21), ('mike', 22)] >>> zip(name,age,tel) [('bob', 20, 131), ('jack', 21, 132)] #如果個數不匹配會被忽略
map()
>>> map(None, name, age) [('bob', 20), ('jack', 21), ('mike', 22)] >>> map(None, name, age, tel) [('bob', 20, 131), ('jack', 21, 132), ('mike', 22, None)] #個數不匹配時,沒有值的會被None代替 >>> a = [1,3,5] >>> b = [2,4,6] >>> map(lambda x,y:x*y, a, b) [2, 12, 30]
reduce()
>>> reduce(lambda x,y:x+y, range(1,101)) 5050
lambda -> 列表表示式
map的例子,可以寫成
print map(lambda x:x*2+10, range(1,11)) print [x*2+10 for x in range(1,11)]
非常的簡潔,易懂。filter的例子可以寫成:
print filter(lambda x:x%3==0, range(1,11)) print [x for x in range(1,11) if x%3 == 0]