1. 程式人生 > >(轉)python函式: 內建函式

(轉)python函式: 內建函式

原文:https://blog.csdn.net/pipisorry/article/details/44755423

https://juejin.im/post/5ae3ee096fb9a07aa7676883

Python內建(built-in)函式隨著python直譯器的執行而建立。在Python的程式中,你可以隨時呼叫這些函式,不需要定義。

Built-in Functions    
abs() dict() help() min() setattr()
all() dir() hex() next() slice()
any() divmod() id() object() sorted()
ascii() enumerate() input() oct() staticmethod()
bin() eval() int() open() str()
bool() exec() isinstance() ord() sum()
bytearray() filter() issubclass() pow() super()
bytes() float() iter() print() tuple()
callable() format() len() property() type()
chr() frozenset() list() range() vars()
classmethod() getattr() locals() repr() zip()
compile() globals() map() reversed() __import__()
complex() hasattr() max() round()  
delattr() hash() memoryview() set()  
[python build-in functions - https://docs.python.org/release/3.4.2/library/functions.html]
[https://docs.python.org/release/2.7.2/library/functions.html]

[定位Python built-in函式的原始碼實現]

皮皮blog

 

 

python常用內建函式
數學運算
abs(-5)                         # 取絕對值,也就是5

round(number, ndigits=None)                      # 四捨五入取整,或者小數保留ndigits位小數,round(2.6)  也就是3.0

pow(2, 3)                        # 相當於2**3,如果是pow(2, 3, 5),相當於2**3 % 5

cmp(2.3, 3.2)                   # 比較兩個數的大小

divmod(9,2)                      # 返回除法結果和餘數

max([1,5,2,9])                   # 求最大值

min([9,2,-4,2])                  # 求最小值

sum([2,-1,9,12])                 # 求和

pow(x,y[,z])
返回 x 的 y 次冪(如果 z 存在的話則以z 為模)。

如果你想計算 x 的 y 次方,以 z 為模,那麼你可以這麼寫:

mod = (x ** y) % z
但是當 x=1234567, y=4567676, z=56 的時候我的電腦足足跑了 64 秒!

不要用 ** 和 % 了,使用 pow(x,y,z) 吧!這個例子可以寫成pow(1234567,4567676,56) ,只用了 0.034 秒就出了結果!

cmp(x,y)
比較兩個物件 x 和 y 。 x<y 的時候返回負數,x==y 的時候返回 0,x>y 的時候返回正數。

def compare(x,y):
if x < y:
return -1
elif x == y:
return 0
else:
return 1
你完全可以使用一句 cmp(x, y) 來替代。


型別轉換
int("5")                        # 轉換為整數 integer

float(2)                         # 轉換為浮點數 float

float(str)

float存在的問題:

1 python ValueError: could not convert string to float.原因:資料中存在空字串'',導致無法轉換成float。

2 精度問題

print(float('39.89245') * 10000)
398924.49999999994
這裡需要使用decimal模組解決,參考[python模組:數字處理:decimal模組]

long("23")                      # 轉換為長整數 long integer

str(2.3)                        # 轉換為字串 string

complex(3, 9)                   # 返回複數 3 + 9i

 

ord("A")                        # "A"字元對應的數值

chr(65)                          # 數值65對應的字元

unichr(65)                       # 數值65對應的unicode字元

 

bool(0)                          # 轉換為相應的真假值,在Python中,0相當於False

在Python中,下列物件都相當於False:[], (),{},0, None,0.0,''

bin(56)                         # 返回一個字串,表示56的二進位制數

hex(56)                         # 返回一個字串,表示56的十六進位制數

oct(56)                         # 返回一個字串,表示56的八進位制數

 

list((1,2,3))                   # 轉換為表 list

tuple([2,3,4])                  # 轉換為定值表 tuple

slice(5,2,-1)                    # 構建下標物件 slice

dict(a=1,b="hello",c=[1,2,3])   # 構建詞典 dictionary

型別轉換
int(str,base) :str為base進位制,預設轉換為十進位制整型

>>> int('11',2)    3

python repr() \str() 函式
將任意值轉為字串:將它傳入repr() 或str() 函式。

函式str() 用於將值轉化為適於人閱讀的形式,而repr() 轉化為供直譯器讀取的形式(如果沒有等價的語法,則會發生SyntaxError 異常)

某物件沒有適於人閱讀的解釋形式的話, str() 會返回與repr()等同的值。很多型別,諸如數值或連結串列、字典這樣的結構,針對各函式都有著統一的解讀方式。字串和浮點數,有著獨特的解讀方式。

>>> s = 'Hello, world.'
>>> str(s)
'Hello, world.'
>>> repr(s)
"'Hello, world.'"     # The repr() of a string adds string quotes and backslashes

 

 

序列操作
all([True, 1, "hello!"])        # 是否所有的元素都相當於True值

any(["", 0, False, [], None])   # 是否有任意一個元素相當於True值

sorted([1,5,3])                  # 返回正序的序列,也就是[1,3,5]

reversed([1,5,3])               # 返回反序的序列,也就是[3,5,1]

all(iterable)
如果可迭代的物件(陣列,字串,列表等,下同)中的元素都是 true (或者為空)的話返回 True 。

_all = True
for item in iterable:
if not item:
_all = False
break
if _all:
# do stuff
更簡便的寫法是:

if all(iterable):
# do stuff
any(iterable)
如果可迭代的物件中任何一個元素為 true 的話返回 True 。如果可迭代的物件為空則返回False 。

_any = False
for item in iterable:
if item:
_any = True
break
if _any:
# do stuff
更簡便的寫法是:

if any(iterable):
# do stuff
sorted(iterable,key,reverse)
Python內建的排序函式sorted可以對iterable物件進行排序,Return a new sorted list from the items in iterable.,官網文件 [py3: sorted(iterable[, key][, reverse])] [py2: sorted(iterable[, cmp[, key[, reverse]]])]。

py2中該函式原型為:sorted(iterable,cmp,key,reverse)

引數解釋:

iterable指定要排序的list或者iterable;

cmp為帶兩個引數的比較函式,指定排序時進行比較的函式,可以指定一個函式或者lambda函式;(從上面看cmp應該是在py3中棄用了)

key 是帶一個引數的比較函式;

reverse升降序選擇,為False或者True(降序);

axis:指定軸進行排序;

Note:

1 list直接排序的通常用法:list.sort(axis = None, key=lambdax:x[1],reverse = True)

2 對dict物件排序sorted(dict)返回的只是dict.keys()的排序結果,也就是sorted(dict)相當於sorted(dict.keys()),dict.keys()是可迭代物件,返回列表。sorted(dict({1: 2})) 返回 [1]。

例子:
(1)用cmp函式排序
>>> list1 = [('david', 90), ('mary',90), ('sara',80),('lily',95)]

>>> sorted(list1,cmp = lambda x,y: cmp(x[1],y[1]))

[('sara', 80), ('david', 90), ('mary', 90), ('lily', 95)]

(2)用key函式排序
>>> list1 = [('david', 90), ('mary',90), ('sara',80),('lily',95)]

>>> sorted(list1,key = lambda list1: list1[1])

[('sara', 80), ('david', 90), ('mary', 90), ('lily', 95)]

(3)用reverse排序
>>> sorted(list1,reverse = True)

[('sara', 80), ('mary', 90), ('lily', 95), ('david', 90)]

(4)用operator.itemgetter函式排序
>>> from operator import itemgetter

>>> sorted(list1, key=itemgetter(1))

[('sara', 80), ('david', 90), ('mary', 90), ('lily', 95)]

>>> sorted(list1, key=itemgetter(0))

[('david', 90), ('lily', 95), ('mary', 90), ('sara', 80)]

(5)多級排序
>>> sorted(list1, key=itemgetter(0,1))

[('david', 90), ('lily', 95), ('mary', 90), ('sara', 80)]

[由 sort 中 key 的用法淺談 python]

[https://wiki.python.org/moin/HowTo/Sorting/]

[Python中的sorted函式以及operator.itemgetter函式]

示例

通過內建函式“sorted”來實現:讓其通過序列長度來從小到大排序

 

建立一個新的元組(s,t),並把它作為“sorted”的第一個引數。我們將從“sorted”得到一個返回的列表。因為我們使用內建的“len”函式作為“key”引數,如果s更短,“sorted”將返回[s,t], 如果t更短,將返回 [t,s]。
operator.itemgetter函式
operator模組提供的itemgetter函式用於獲取物件的哪些維的資料,引數為一些序號(即需要獲取的資料在物件中的序號)。
a = [1,2,3]
>>> b=operator.itemgetter(1)      //定義函式b,獲取物件的第1個域的值
>>> b(a)
2
>>> b=operator.itemgetter(1,0)   //定義函式b,獲取物件的第1個域和第0個的值
>>> b(a)
(2, 1)
Note:operator.itemgetter函式獲取的不是值,而是定義了一個函式,通過該函式作用到物件上才能獲取值。


類,物件,屬性
# define class
class Me(object):
def test(self):
print "Hello!"

def new_test():
print "New Hello!"

me = Me()
hasattr(me, "test")              # 檢查me物件是否有test屬性
getattr(me, "test")              # 返回test屬性

setattr(me, "test", new_test)    # 將test屬性設定為new_test

delattr(me, "test")              # 刪除test屬性

isinstance(me, Me)               # me物件是否為Me類生成的物件 (一個instance)

issubclass(Me, object)           # Me類是否為object類的子類

isinstance(object, classinfo)
如果 object 引數是 classinfo 引數的一個例項或者子類(直接或者間接)的話返回 True 。

當你想檢驗一個物件的型別的時候,第一個想到的應該是使用 type() 函式。

if type(obj) == type(dict):
# do stuff
elif type(obj) == type(list):
# do other stuff
...
或者你可以這麼寫:

if isinstance(obj, dict):
# do stuff
elif isinstance(obj, list):
# do other stuff
...


編譯,執行
repr(me)                         # 返回物件的字串表達

compile("print('Hello')",'test.py','exec')       # 編譯字串成為code物件

eval("1 + 1")                     # 解釋字串表示式。引數也可以是compile()返回的code物件

exec("print('Hello')")            # 解釋並執行字串,print('Hello')。引數也可以是compile()返回的code物件

對Python表示式求值eval和literal_eval
我們都知道eval函式,但是我們知道literal_eval函式麼?

import ast

my_list = ast.literal_eval(expr)

來代替以下這種操作:

expr = "[1, 2, 3]"

my_list = eval(expr)

皮皮blog

 

 

其它常用函式
輸入輸出
input("Please input:")           # 等待輸入

print("Hello World!)

文字檔案的輸入輸出 open()


變數
globals()                         # 返回全域性名稱空間,比如全域性變數名,全域性函式名

locals()                          # 返回區域性名稱空間

Local函式
想讓程式碼看起來更加簡明,可以利用 Python 的內建函式 locals() 。它返回的字典對所有區域性變數的名稱與值進行對映。

def test(c):
a = {}
a[0] = 3
b = 4
print(locals())

if __name__ == '__main__':
test(8)

{'c': 8, 'b': 4, 'a': {0: 3}}
Note:使用 locals() 時要注意是它將包括 所有 的區域性變數,它們可能比你想訪問的要多。也包括傳入函式的引數。


基本資料型別
type() dir() len()

物件自檢dir()
在Python 中你可以通過dir() 函式來檢查物件。正如下面這個例子:

>>> foo = [1, 2, 3, 4]

>>> dir(foo)

['__add__', '__class__', '__contains__',

'__delattr__', '__delitem__', '__delslice__', ... ,

'extend', 'index', 'insert', 'pop', 'remove',

'reverse', 'sort']

[python模組匯入及屬性]


迴圈設計
range() enumerate() zip()

range()
range好像只能生成整數型別的range,但是可以使用np.arange(0,1,0.1)來生成float型別的range。

列舉函式enumerate(iterable [,start=0])
如果你以前寫過 C 語言,那麼你可能會這麼寫:

for i in range(len(list)):
# do stuff with list[i], for example, print it
print i, list[i]
噢,不用那麼麻煩!你可以使用 enumerate() 來提高可讀性。

for i, item in enumerate(list):
# so stuff with item, for example print it
print i, item
利用enumerate()函式,可以在每次迴圈中同時得到下標和元素

S = 'abcdef'
for (index,char) in enumerate(S):
print index
print char
實際上,enumerate()在每次迴圈中,返回的是一個包含兩個元素的定值表(tuple),兩個元素分別賦予index和char

enumerate函式還可以接收第二個引數。

>>> list(enumerate('abc', 1))

[(1, 'a'), (2, 'b'), (3, 'c')]

zip([iterable,])
這個函式返回一個含元組的列表,具體請看例子。

l1 = ('You gotta', 'the')
l2 = ('love', 'built-in')
out = []
if len(l1) == len(l2):
for i in range(len(l1)):
out.append((l1[i], l2[i]))
# out = [('You gotta', 'love'), ('the', 'built-in)]
或者這麼寫:

l1 = ['You gotta', 'the']
l2 = ['love', 'built-in']
out = zip(l1, l2) # [('You gotta', 'love'), ('the', 'built-in)]
如果你想得到倒序的話加上 * 操作符就可以了。

print zip(*out)
# [('You gotta', 'the'), ('love', 'built-in')]
Note: zip函式中的引數len不同,則只取len短的為準

用列表解析實現zip


[用列表解析實現‘zip" ]

Zipping and unzipping lists and iterables
>>> a = [1, 2, 3]
>>> b = ['a', 'b', 'c']
>>> z = zip(a, b)
>>> z
[(1, 'a'), (2, 'b'), (3, 'c')]
>>> zip(*z)
[(1, 2, 3), ('a', 'b', 'c')]
多個序列的zip
如果你多個等長的序列,然後想要每次迴圈時從各個序列分別取出一個元素,可以利用zip()方便地實現:

ta = [1,2,3]
tb = [9,8,7]
tc = ['a','b','c']
for (a,b,c) in zip(ta,tb,tc):
print(a,b,c)
每次迴圈時,從各個序列分別從左到右取出一個元素,合併成一個tuple,然後tuple的元素賦予給a,b,c

zip()函式的功能,就是從多個列表中,依次各取出一個元素。每次取出的(來自不同列表的)元素合成一個元組,合併成的元組放入zip()返回的列表中。zip()函式起到了聚合列表的功能。

x = [1,23,45]
print(x)
y = [8,43,74]
print(y)
z = [3,34,39]
print(z)
print(list(zip(x,y,z)))
[(1, 8, 3), (23, 43, 34), (45, 74, 39)]
使用zip分組相鄰列表項
>>> a =[1,2,3,4,5,6]
>>> # Using iterators
>>> group_adjacent=lambdaa, k:zip(*([iter(a)]*k))
>>> group_adjacent(a,3)
[(1,2,3), (4,5,6)]
>>> group_adjacent(a,2)
[(1,2), (3,4), (5,6)]
>>> group_adjacent(a,1)
[(1,), (2,), (3,), (4,), (5,), (6,)]
>>> # Using slices
>>> fromitertoolsimportislice
>>> group_adjacent=lambdaa, k:zip(*(islice(a, i,None, k)fori inrange(k)))
>>> group_adjacent(a,3)
[(1,2,3), (4,5,6)]
>>> group_adjacent(a,2)
[(1,2), (3,4), (5,6)]
>>> group_adjacent(a,1)
[(1,), (2,), (3,), (4,), (5,), (6,)]
使用zip & iterators實現推拉窗(n-grams)
>>> fromitertoolsimportislice
>>> defn_grams(a, n):
... z =(islice(a, i,None)foriin range(n))
... returnzip(*z)
...
>>> a =[1,2,3,4,5,6]
>>> n_grams(a, 3)
[(1,2,3), (2,3,4), (3,4,5), (4,5,6)]
>>> n_grams(a, 2)
[(1,2), (2,3), (3,4), (4,5), (5,6)]
>>> n_grams(a,4)
[(1,2,3,4), (2,3,4,5), (3,4,5,6)]
使用zip反相字典物件
>>> m ={"a":1,"b":2,"c":3,"d":4}
>>> zip(m.values(), m.keys())
[(1,"a"), (3,"c"), (2,"b"), (4,"d")]
>>> mi =dict(zip(m.values(), m.keys()))
>>> mi
{1:"a",2:"b",3:"c",4:"d"}
迴圈物件
iter()

 

函式物件
map() filter() reduce()

皮皮blog

 


簡單伺服器
你是否想要快速方便的共享某個目錄下的檔案呢?

# Python2 python -m SimpleHTTPServer # Python 3 python3 -m http.server

這樣會為啟動一個伺服器。

使用C風格的大括號代替Python縮排來表示作用域
from __future__ import braces

三元運算
三元運算是if-else 語句的快捷操作,也被稱為條件運算。這裡有幾個例子可以供你參考,它們可以讓你的程式碼更加緊湊,更加美觀。

[on_true] if [expression] else [on_false]

x, y = 50, 25

small = x if x < y else y

from:http://blog.csdn.net/pipisorry/article/details/44755423

ref: [Python build-in functions]

Nifty Python tricks

Python built-in functions are awesome. Use them!

Python: Tips, Tricks and Idioms

30 Python Language Features and Tricks You May Not Know About
---------------------
作者:-柚子皮-
來源:CSDN
原文:https://blog.csdn.net/pipisorry/article/details/44755423
版權宣告:本文為博主原創文章,轉載請附上博文連結!