熟練掌握Python的內(nèi)置函數(shù),加快編程速度-創(chuàng)新互聯(lián)

內(nèi)置函數(shù)概覽

創(chuàng)新互聯(lián)專業(yè)為企業(yè)提供錯那網(wǎng)站建設(shè)、錯那做網(wǎng)站、錯那網(wǎng)站設(shè)計、錯那網(wǎng)站制作等企業(yè)網(wǎng)站建設(shè)、網(wǎng)頁設(shè)計與制作、錯那企業(yè)網(wǎng)站模板建站服務(wù),十多年錯那做網(wǎng)站經(jīng)驗,不只是建網(wǎng)站,更提供有價值的思路和整體網(wǎng)絡(luò)服務(wù)。

Python 2.7 的所有內(nèi)置函數(shù)共有80個。熟練記住和使用這些內(nèi)置函數(shù),將大大提高寫Python代碼的速度和代碼的優(yōu)雅程度。

以下代碼示例用的是ipython,一個比官方解釋器好很多的解釋器,值的學(xué)習(xí)和使用。

數(shù)學(xué)相關(guān)的內(nèi)置函數(shù)

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

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

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

complex(real[, imag]) 生成一個復(fù)數(shù)

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

divmod(x, y) 返回x除以y的商和余數(shù)

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

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

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() 函數(shù)
pow(x, y[, z]) 返回x的y次冪,如果有參數(shù)z則返回冪除以z的余數(shù)(對z取模)

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

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

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

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]) 對一個數(shù)字序列求和,start為起始位置,默認從0開始

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

數(shù)字、字符轉(zhuǎn)換

  • bin(number), hex(number), oct(number)
    把一個數(shù)字轉(zhuǎn)換成二進制、十六進制、八進制字符串
    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) 把一個整數(shù)轉(zhuǎn)換為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) 把一個整數(shù)轉(zhuǎn)換為Unicode字符, 0 <= i <= 0x10ffff

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

ord(c) 把一個ascii碼字符轉(zhuǎn)換為整數(shù)

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

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

float(x), int(x), long(x) 浮點數(shù)、整數(shù)、長整數(shù)之間的轉(zhuǎn)換

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=’’) 把一個對象轉(zhuǎn)換成字符串:

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) 返回一個對象的元素個數(shù)

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

map(function, sequence[, sequence, …]) 把一個函數(shù)應(yīng)用于每一個元素并返回一個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, …]) 把函數(shù)作用于初始兩個元素,并把返回值和下一個元素作為輸入調(diào)用函數(shù),依次迭代所有元素

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

zip(seq1 [, seq2 […]]) -> [(seq1[0], seq2[0] …), (…)]
把多個序列合并成一個序列l(wèi)ist

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

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

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) 對一個序列排序
可選參數(shù)cmp、key和reverse與list.sort()方法的參數(shù)含義相同(在可變的序列類型一節(jié)描述)。
cmp指定一個自定義的帶有兩個參數(shù)的比較函數(shù)(可迭代的元素),它應(yīng)該根據(jù)第一個參數(shù)是小于、等于還是大于第二個參數(shù)返回負數(shù)、零或者正數(shù):cmp=lambda x,y: cmp(x.lower(), y.lower())。默認值是None。
key指定一個帶有一個參數(shù)的函數(shù),它用于從每個列表元素選擇一個比較的關(guān)鍵字:key=str.lower。默認值是None(直接比較元素)。
reverse是一個布爾值。如果設(shè)置為True,那么列表元素以反向比較排序。
通常情況下,key和reverse轉(zhuǎn)換處理比指定一個等同的cmp函數(shù)要快得多。這是因為cmp為每個元素調(diào)用多次但是key和reverse只會觸摸每個元素一次。使用functools.cmp_to_key()來轉(zhuǎn)換舊式的cmp函數(shù)為key函數(shù)。

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)]

數(shù)據(jù)結(jié)構(gòu)

bytearray() dict() frozenset() list() set() tuple()
python里面常用的數(shù)據(jù)結(jié)構(gòu)有列表(list)、字典(dict)、集合(set)、元組(tuple)

對象、類型

以下是一些類(class)和類型相關(guān)的函數(shù),比較不常用,可以查看手冊詳細了解。
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()

不重要的內(nèi)置函數(shù)

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

ipython

ipython是一個非常好的交互式python解釋器,它查看一個函數(shù)或類的用法的方法有:

help(xxx)
xxx?
查看一個類/對象的成員函數(shù)或變量時,在類或?qū)ο笞兞亢竺孑斎?后按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


文章版權(quán)歸屬于 【 猿人學(xué)Python】www.yuanrenxue.com

另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)cdcxhl.cn,海內(nèi)外云服務(wù)器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國服務(wù)器、虛擬主機、免備案服務(wù)器”等云主機租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務(wù)可用性高、性價比高”等特點與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場景需求。

本文標題:熟練掌握Python的內(nèi)置函數(shù),加快編程速度-創(chuàng)新互聯(lián)
URL分享:http://muchs.cn/article46/dspjeg.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供定制網(wǎng)站、網(wǎng)站設(shè)計公司、響應(yīng)式網(wǎng)站、網(wǎng)站制作、App設(shè)計、小程序開發(fā)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

營銷型網(wǎng)站建設(shè)