python補充最常見的內置函數


最常見的內置函數是:

print("Hello World!")

數學運算

abs(-5)                         # 取絕對值,也就是5

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])                 # 求和

 

類型轉換

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

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

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

 

序列操作

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

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

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

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

 

類,對象,屬性

  1. # define class  
  2. class Me(object):  
  3.     def test(self):  
  4.         print "Hello!"  
  5.   
  6. def new_test():  
  7.     print "New Hello!"  
  8.   
  9. 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類的子類

 

編譯,執行

repr(me)                         # 返回對象的字符串表達

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

eval("1 + 1")                     # 解釋字符串表達式。參數也可以是compile()返回的code對象

exec("print('Hello')")            # 解釋並執行字符串,print('Hello')。參數也可以是compile()返回的code對象

 

 

Python內置(built-in)函數隨着python解釋器的運行而創建。在Python的程序中,你可以隨時調用這些函數,不需要定義。最常見的內置函數是:

 

print("Hello World!")

 

Python教程中,我們已經提到下面一些內置函數:

 

基本數據類型 type()

 

反過頭來看看 dir() help() len()

 

詞典 len()

 

文本文件的輸入輸出 open()

 

循環設計 range() enumerate() zip()

 

循環對象 iter()

 

函數對象 map() filter() reduce()

 

 

 

下面我采取的都是實際的參數,你可以直接在命令行嘗試效果。

 

數學運算

 

abs(-5)                          # 取絕對值,也就是5

 

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])                 # 求和

 

 

 

類型轉換

 

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

 

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

 

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

 

 

 

序列操作

 

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

 

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

 

 

 

 

 

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

 

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

 

 

 

類,對象,屬性

 

復制代碼
# 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類的子類

 

 

 

編譯,執行

 

repr(me)                          # 返回對象的字符串表達

 

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

 

eval("1 + 1")                     # 解釋字符串表達式。參數也可以是compile()返回的code對象

 

exec("print('Hello')")            # 解釋並執行字符串,print('Hello')。參數也可以是compile()返回的code對象

 

 

 

其他

input("Please input:")           # 等待輸入

globals()                         # 返回全局命名空間,比如全局變量名,全局函數名

locals()                          # 返回局部命名空間

 

基本數據類型  type() dir() len()

文本文件的輸入輸出 open()

循環設計 range() enumerate() zip()

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

循環對象 iter()

函數對象 map() filter() reduce()

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短的為准

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()函數起到了聚合列表的功能。

=[1,2,3,4,5,6]
>>>  # Using iterators
>>> group_adjacent = lambda a, 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
>>>  from itertools import islice
>>> group_adjacent = lambda a, k: zip ( * (islice(a, i, None , k) for in range (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)
>>>  from itertools import islice
>>>  def n_grams(a, n):
... z  = (islice(a, i, None ) for i in  range (n))
...  return zip ( * 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 }
>>> m.items()
[( "a" , 1 ), ( "c" , 3 ), ( "b" , 2 ), ( "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" }



枚舉函數enumerate

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


簡單服務器

你是否想要快速方便的共享某個目錄下的文件呢?

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

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


最大 & 最小元素(heapq.nlargest and heapq.nsmallest)

 

>>> a = [random.randint( 0 , 100 ) for __ in xrange ( 100 )]
>>> heapq.nsmallest( 5 , a)
[ 3 , 3 , 5 , 6 , 8 ]
>>> heapq.nlargest( 5 , a)
[ 100 , 100 , 99 , 98 , 98 ]


使用C風格的大括號代替Python縮進來表示作用域

from __future__ import braces

對Python表達式求值

我們都知道eval函數,但是我們知道literal_eval函數么?

import ast

my_list = ast.literal_eval(expr)

來代替以下這種操作:

expr = "[1, 2, 3]"

my_list = eval(expr)

對象自檢

在Python 中你可以通過dir() 函數來檢查對象。正如下面這個例子:

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

>>> dir(foo)

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

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

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

'reverse', 'sort']


[python模塊導入及屬性]

三元運算

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

[on_true] if [expression] else [on_false]

x, y = 50, 25

small = x if x < y else y

 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

cmp(x,y)

比較兩個對象 x yx<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) 來替代。

dict([arg])

使用 arg 提供的條目生成一個新的字典。

arg 通常是未知的,但是它很方便!比如說,如果我們想把一個含兩個元組的列表轉換成一個字典,我們可以這么做。

l = [('Knights', 'Ni'), ('Monty', 'Python'), ('SPAM', 'SPAAAM')] d = dict() for tuple in l: d[tuple[0]] = tuple[1] # {'Knights': 'Ni', 'Monty': 'Python', 'SPAM': 'SPAAAM'} 

或者這樣:

l = [('Knights', 'Ni'), ('Monty', 'Python'), ('SPAM', 'SPAAAM')] d = dict(l) # {'Knights': 'Ni', 'Monty': 'Python', 'SPAM': 'SPAAAM'} 

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
...

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 秒就出了結果!

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() 時要注意是它將包括 所有 的局部變量,它們可能比你想訪問的要多。也包括傳入函數的參數。

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

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函數獲取的不是值,而是定義了一個函數,通過該函數作用到對象上才能獲取值。

皮皮blog


python內置排序函數

sorted(iterable,cmp,key,reverse)

Python內置的排序函數sorted可以對list或者iterator進行排序,官網文檔見:http://docs.python.org/2/library/functions.html?highlight=sorted#sorted,該函數原型為:

sorted(iterable[, cmp[, key[, reverse]]])

參數解釋:

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

cmp為帶兩個參數的比較函數,指定排序時進行比較的函數,可以指定一個函數或者lambda函數

key 是帶一個參數的比較函數;

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

axis:指定軸進行排序;

通常用法:list.sort(axis = None, key=lambda x:x[1], reverse = True)

例子:
(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函數]

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

ref:Python 內置函數

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM