熟練掌握Python的內置函數,加快編程速度

圖片描述python

內置函數概覽git

Python 2.7 的全部內置函數共有80個。熟練記住和使用這些內置函數,將大大提升寫Python代碼的速度和代碼的優雅程度。數據結構

如下代碼示例用的是ipython,一個比官方解釋器好不少的解釋器,值的學習和使用。app

數學相關的內置函數ide

abs(x) 返回一個數字的絕對值函數

In [18]: abs(3.14)
Out[18]: 3.14

In [19]: abs(-3.14)
Out[19]: 3.14

complex(real[, imag]) 生成一個複數學習

In [135]: complex(1,3)
Out[135]: (1+3j)

divmod(x, y) 返回x除以y的商和餘數網站

In [143]: divmod(12, 7)
Out[143]: (1, 5)

max(iterable[, key]) 返回一個序列的最大元素ui

In [157]: max([(1,2,3), (4,5,6), (23,4,1,)], key=lambda a: a[-1])
Out[157]: (4, 5, 6)

In [158]: max(1,2,3,4,4,5)
Out[158]: 5

In [159]: max([(1,2,3), (4,5,6), (23,4,1,)])
Out[159]: (23, 4, 1)

In [160]: max([(1,2,3), (4,5,6), (23,4,1,)], key=lambda a: a[-1])
Out[160]: (4, 5, 6)

In [161]: max([{'age':10, 'name': 'aaa'}, {'age': 12, 'name': 'bb'}], key=lambda a: a['age'])
Out[161]: {'age': 12, 'name': 'bb'}

min(iterable[, key]) 返回一個序列的最小元素
參見上面的max() 函數
pow(x, y[, z]) 返回x的y次冪,若是有參數z則返回冪除以z的餘數(對z取模)code

In [166]: pow(2,3)
Out[166]: 8

In [167]: pow(2,3,5)
Out[167]: 3

round(number[, ndigits]) 返回一個數的四捨五入值,給出ndigits則四捨五入到第n位小數

In [170]: round(3.45)
Out[170]: 3.0

In [171]: round(3.55)
Out[171]: 4.0

In [172]: round(3.55345, 3)
Out[172]: 3.553

sum(sequence[, start]) 對一個數字序列求和,start爲起始位置,默認從0開始

In [175]: sum([1,2,3,4])
Out[175]: 10

數字、字符轉換

bin(number), hex(number), oct(number)
把一個數字轉換成二進制、十六進制、八進制字符串

In [204]: print bin(20), hex(16), oct(9)
0b10100 0x10 011

bool(x) 若是x是真則返回True,不然返回False

In [184]: print bool(3), bool('a')
True True

In [185]: print bool(0), bool(''), bool(None)
False False False

chr(i) 把一個整數轉換爲ascii碼字符, 0<= i < 256

In [188]: chr(320)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-188-5b2996ffe50c> in <module>()
----> 1 chr(320)

ValueError: chr() arg not in range(256)

In [189]: chr(65)
Out[189]: 'A'

In [190]: chr(0)
Out[190]: '\x00'

unichr(i) 把一個整數轉換爲Unicode字符, 0 <= i <= 0x10ffff

In [225]: unichr(1245)
Out[225]: u'\u04dd'

ord(c) 把一個ascii碼字符轉換爲整數

In [192]: ord('a')
Out[192]: 97

In [193]: ord('\x23')
Out[193]: 35

float(x), int(x), long(x) 浮點數、整數、長整數之間的轉換

In [196]: print float('13'), float(13)
13.0 13.0

In [197]: print int('14'), int(14)
14 14

In [198]: print long('15'), long(15)
15 15

format(value[, format_spec]) 對value按照format_spec格式化

In [212]: format(123, '05d')
Out[212]: '00123'

以上等同於 print ‘%05d’ % 123

hash(ojbect) 對object計算hash值

In [218]: hash(123)
Out[218]: 123

In [219]: hash('abc')
Out[219]: 1453079729188098211

str(object=’’) 把一個對象轉換成字符串:

In [221]: str(123)
Out[221]: '123'

In [222]: str([1,2,3])
Out[222]: '[1, 2, 3]'

In [223]: str({'a': 1, 'b': 2})
Out[223]: "{'a': 1, 'b': 2}"

輸入輸出

file(name[, mode[, buffering]]), open 打開一個文件

In [251]: file('abc.txt', 'w')
Out[251]: <open file 'abc.txt', mode 'w' at 0x7f93e727a660>

In [252]: open('abc.txt', 'w')
Out[252]: <open file 'abc.txt', mode 'w' at 0x7f93e727a780>
input([prompt]), raw_input() 從終端輸入信息
In [253]: input('pls input a number >>')
pls input a number >>123
Out[253]: 123

序列處理

all(iterable) 若是一個序列全部值都爲真就返回True,不然返回False
any(iterable) 若是一個序列至少有一個爲真就返回True, 不然False

In [255]: all([1,2,3,4])
Out[255]: True

In [256]: all([1,2,3,4, 0])
Out[256]: False

In [257]: any([1,2,3,4, 0])
Out[257]: True

enumerate(iterable[, start]) 遍歷一個序列的元素及其索引

In [261]: for i, value in enumerate(['a', 'b', 'c']):
   .....:     print i, value
   .....: 
0 a
1 b
2 c

filter(function or None, squence) 返回知足function(item)爲True的元素

In [263]: filter(lambda x: x>3, [1,2,3,4,5])
Out[263]: [4, 5]

iter(collection) 返回一個對象的迭代器
讀取文件的時候比較有用:

with open("mydata.txt") as fp:
    for line in iter(fp.readline, "STOP"):
        process_line(line)

len(object) 返回一個對象的元素個數

In [267]: len('abc'), len([1,2,3])
Out[267]: (3, 3)

map(function, sequence[, sequence, …]) 把一個函數應用於每個元素並返回一個list

In [269]: map(lambda x: x+3, [1,2,3])
Out[269]: [4, 5, 6]

In [270]: a = [1,2]; b = ['a', 'b']; c = ('x', 'y')

In [271]: map(None, a, b, c)
Out[271]: [(1, 'a', 'x'), (2, 'b', 'y')]

reduce(function, sequence[, sequence, …]) 把函數做用於初始兩個元素,並把返回值和下一個元素做爲輸入調用函數,依次迭代全部元素

In [281]: reduce(lambda a, b: a-b, [1,2,3])
Out[281]: -4

zip(seq1 [, seq2 […]]) -> [(seq1[0], seq2[0] …), (…)]
把多個序列合併成一個序列list

In [283]: zip([1,2,3], ('a', 'b', 'c'))
Out[283]: [(1, 'a'), (2, 'b'), (3, 'c')]

range() xrange() 返回一個整數序列

In [274]: [x for x in xrange(10)]
Out[274]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In [275]: [x for x in xrange(5, 10)]
Out[275]: [5, 6, 7, 8, 9]

In [276]: [x for x in xrange(5, 10, 2)]
Out[276]: [5, 7, 9]

In [277]: range(10)
Out[277]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In [278]: range(5, 10)
Out[278]: [5, 6, 7, 8, 9]

In [279]: range(5, 10, 2)
Out[279]: [5, 7, 9]

sorted(iterable, cmp=None, key=None, reverse=False) 對一個序列排序
可選參數cmp、key和reverse與list.sort()方法的參數含義相同(在可變的序列類型一節描述)。
cmp指定一個自定義的帶有兩個參數的比較函數(可迭代的元素),它應該根據第一個參數是小於、等於仍是大於第二個參數返回負數、零或者正數:cmp=lambda x,y: cmp(x.lower(), y.lower())。默認值是None。
key指定一個帶有一個參數的函數,它用於從每一個列表元素選擇一個比較的關鍵字:key=str.lower。默認值是None(直接比較元素)。
reverse是一個布爾值。若是設置爲True,那麼列表元素以反向比較排序。
一般狀況下,key和reverse轉換處理比指定一個等同的cmp函數要快得多。這是由於cmp爲每一個元素調用屢次可是key和reverse只會觸摸每一個元素一次。使用functools.cmp_to_key()來轉換舊式的cmp函數爲key函數。

In [288]: sorted(d.items(), key=lambda a: a[1])
Out[288]: [('a', 3), ('b', 4)]

In [289]: sorted(d.items(), key=lambda a: a[1], rev)

In [289]: sorted(d.items(), key=lambda a: a[1], reverse=True)
Out[289]: [('b', 4), ('a', 3)]

In [290]: sorted(d.items(), cmp=lambda a, b: cmp(a[1], b[1]))
Out[290]: [('a', 3), ('b', 4)]

數據結構

bytearray() dict() frozenset() list() set() tuple()
python裏面經常使用的數據結構有列表(list)、字典(dict)、集合(set)、元組(tuple)

對象、類型

如下是一些類(class)和類型相關的函數,比較不經常使用,能夠查看手冊詳細瞭解。
basestring() callable() classmethod() staticmethod() property() cmp() compile() delattr() getattr() setattr() hasattr() dir() globals() locals() vars() help() id() isinstance() issubclass() object() memoryview() repr() super() type() unicode() import() eval() execfile()

不重要的內置函數

apply() buffer() coerce() intern()

ipython

ipython是一個很是好的交互式python解釋器,它查看一個函數或類的用法的方法有:

help(xxx)
xxx?
查看一個類/對象的成員函數或變量時,在類或對象變量後面輸入.後按tab鍵:

In [292]: import time

In [293]: time.
time.accept2dyear  time.clock         time.gmtime        time.sleep         time.struct_time   time.tzname        
time.altzone       time.ctime         time.localtime     time.strftime      time.time          time.tzset         
time.asctime       time.daylight      time.mktime        time.strptime      time.timezone      

In [293]: time.ti
time.time      time.timezone  

In [293]: time.time?
Docstring:
time() -> floating point number

Return the current time in seconds since the Epoch.
Fractions of a second may be present if the system clock provides them.
Type:      builtin_function_or_method

文章首發於個人我的博客,同時我也在猿人學網站上寫Python教程你也能夠關注個人我的公衆號:猿人學Python

相關文章
相關標籤/搜索