1. 程式人生 > 其它 >Python3內建函式

Python3內建函式

  

  以上函式從上往下,從做往右來演示。

  官方文件: https://docs.python.org/3.7/library/functions.html

abs() 函式

  描述

  abs() 函式返回數字的絕對值。

  語法

  以下是 abs() 方法的語法:

abs( x )

  引數

  x -- 數值表示式,可以是整數,浮點數,複數。

  返回值

  函式返回 x(數字)的絕對值,如果引數是一個複數,則返回它的大小。

  例項

  以下展示了使用 abs() 方法的例項:

#!/usr/bin/python3

print ("abs(-40) : ", abs(-40))
print
("abs(100.10) : ", abs(100.10)) 以上例項執行後輸出結果為: abs(-40) : 40 abs(100.10) : 100.1

all() 函式

  描述

  all() 函式用於判斷給定的可迭代引數 iterable 中的所有元素是否都為 TRUE,如果是返回 True,否則返回 False。

  元素除了是 0、空、None、False 外都算 True。

  函式等價於:

def all(iterable):
    for element in iterable:
        if not element:
            return False
    
return True

  Python 2.5 以上版本可用。

  語法

  以下是 all() 方法的語法:

  all(iterable)

  引數

  iterable -- 元組或列表。

  返回值

  如果iterable的所有元素不為0、''、False或者iterable為空,all(iterable)返回True,否則返回False;

  注意:空元組、空列表返回值為True,這裡要特別注意。

  例項

  以下展示了使用 all() 方法的例項:

>>> all(['a', 'b', 'c', 'd'])  # 列表list,元素都不為空或0
True
>>> all(['a', 'b', '', 'd']) # 列表list,存在一個為空的元素 False >>> all([0, 1,2, 3]) # 列表list,存在一個為0的元素 False >>> all(('a', 'b', 'c', 'd')) # 元組tuple,元素都不為空或0 True >>> all(('a', 'b', '', 'd')) # 元組tuple,存在一個為空的元素 False >>> all((0, 1, 2, 3)) # 元組tuple,存在一個為0的元素 False >>> all([]) # 空列表 True >>> all(()) # 空元組 True

any() 函式

  描述

  any() 函式用於判斷給定的可迭代引數 iterable 是否全部為 False,則返回 False,如果有一個為 True,則返回 True。

  元素除了是 0、空、FALSE 外都算 TRUE。

  函式等價於:

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False

  Python 2.5 以上版本可用。

  語法

  以下是 any() 方法的語法:

  any(iterable)

  引數

  iterable -- 元組或列表。

  返回值

  如果都為空、0、false,則返回false,如果不都為空、0、false,則返回true。

  例項

  以下展示了使用 any() 方法的例項:

>>>any(['a', 'b', 'c', 'd'])  # 列表list,元素都不為空或0
True
 
>>> any(['a', 'b', '', 'd'])   # 列表list,存在一個為空的元素
True
 
>>> any([0, '', False])        # 列表list,元素全為0,'',false
False
 
>>> any(('a', 'b', 'c', 'd'))  # 元組tuple,元素都不為空或0
True
 
>>> any(('a', 'b', '', 'd'))   # 元組tuple,存在一個為空的元素
True
 
>>> any((0, '', False))        # 元組tuple,元素全為0,'',false
False
  
>>> any([]) # 空列表
False
 
>>> any(()) # 空元組
False

ascii() 函式

描述

ascii() 函式類似 repr() 函式, 返回一個表示物件的字串, 但是對於字串中的非 ASCII 字元則返回通過 repr() 函式使用 \x, \u 或 \U 編碼的字元。 生成字串類似 Python2 版本中 repr() 函式的返回值。

語法

以下是 ascii() 方法的語法:

ascii(object)

引數

object -- 物件。

返回值

返回字串。

例項

以下展示了使用 ascii() 方法的例項

>>> ascii('lizexiong')

"'lizexiong'"

 

bin() 函式

描述

bin() 返回一個整數 int 或者長整數 long int 的二進位制表示。

語法

以下是 bin() 方法的語法:

bin(x)

引數

x -- int 或者 long int 數字

返回值

字串。

例項

以下展示了使用 bin 函式的例項:

>>>bin(10)

'0b1010'

>>> bin(20)

'0b10100'

 

bool() 函式

描述

bool() 函式用於將給定引數轉換為布林型別,如果沒有引數,返回 False。

bool 是 int 的子類。

語法

以下是 bool() 方法的語法:

class bool([x])

引數

x -- 要進行轉換的引數。

返回值

返回 True 或 False。

例項

以下展示了使用 bool 函式的例項:

>>>bool()

False

>>> bool(0)

False

>>> bool(1)

True

>>> bool(2)

True

>>> issubclass(bool, int)  # bool 是 int 子類

True

 

bytearray() 函式

描述

bytearray() 方法返回一個新位元組陣列。這個數組裡的元素是可變的,並且每個元素的值範圍: 0 <= x < 256。

語法

bytearray()方法語法:

class bytearray([source[, encoding[, errors]]])

引數

如果 source 為整數,則返回一個長度為 source 的初始化陣列;

如果 source 為字串,則按照指定的 encoding 將字串轉換為位元組序列;

如果 source 為可迭代型別,則元素必須為[0 ,255] 中的整數;

如果 source 為與 buffer 介面一致的物件,則此物件也可以被用於初始化 bytearray。

如果沒有輸入任何引數,預設就是初始化陣列為0個元素。

返回值

返回新位元組陣列。

例項

以下例項展示了 bytearray() 的使用方法:

>>>bytearray()

bytearray(b'')

>>> bytearray([1,2,3])

bytearray(b'\x01\x02\x03')

>>> bytearray('lizexiong', 'utf-8')

bytearray(b'lizexiong')

>>> 

 

bytes 函式

描述

bytes 函式返回一個新的 bytes 物件,該物件是一個 0 <= x < 256 區間內的整數不可變序列。它是 bytearray 的不可變版本。

語法

以下是 bytes 的語法:

class bytes([source[, encoding[, errors]]])

引數

如果 source 為整數,則返回一個長度為 source 的初始化陣列;

如果 source 為字串,則按照指定的 encoding 將字串轉換為位元組序列;

如果 source 為可迭代型別,則元素必須為[0 ,255] 中的整數;

如果 source 為與 buffer 介面一致的物件,則此物件也可以被用於初始化 bytearray。

如果沒有輸入任何引數,預設就是初始化陣列為0個元素。

返回值

返回一個新的 bytes 物件。

例項

以下展示了使用 bytes 的例項:

>>>a = bytes([1,2,3,4])

>>> a

b'\x01\x02\x03\x04'

>>> type(a)

<class 'bytes'>

>>> 

>>> a = bytes('hello','ascii')

>>> 

>>> a

b'hello'

>>> type(a)

<class 'bytes'>

>>> 

 

callable() 函式

描述

callable() 函式用於檢查一個物件是否是可呼叫的。如果返回 True,object 仍然可能呼叫失敗;但如果返回 False,呼叫物件 object 絕對不會成功。

對於函式、方法、lambda 函式、 類以及實現了 __call__ 方法的類例項, 它都返回 True。

語法

callable()方法語法:

callable(object)

引數

object -- 物件

返回值

可呼叫返回 True,否則返回 False。

例項

以下例項展示了 callable() 的使用方法:

>>>callable(0)

False

>>> callable("lizexiong")

False

 

>>> def add(a, b):

...     return a + b

...

>>> callable(add)             # 函式返回 True

True

>>> class A:                  # 類

...     def method(self):

...             return 0

...

>>> callable(A)               # 類返回 True

True

>>> a = A()

>>> callable(a)               # 沒有實現 __call__, 返回 False

False

>>> class B:

...     def __call__(self):

...             return 0

...

>>> callable(B)

True

>>> b = B()

>>> callable(b)               # 實現 __call__, 返回 True

True

 

chr() 函式

描述

chr() 用一個整數作引數,返回一個對應的字元。

語法

以下是 chr() 方法的語法:

chr(i)

引數

i -- 可以是 10 進位制也可以是 16 進位制的形式的數字,數字範圍為 0 到 1,114,111 (16 進製為0x10FFFF)。

返回值

返回值是當前整數對應的 ASCII 字元。

例項

以下展示了使用 chr() 方法的例項:

>>>chr(0x30)

'0'

>>> chr(97)

'a'

>>> chr(8364)

'€'

 

classmethod 修飾符

描述

classmethod 修飾符對應的函式不需要例項化,不需要 self 引數,但第一個引數需要是表示自身類的 cls 引數,可以來呼叫類的屬性,類的方法,例項化物件等。

語法

classmethod 語法:

classmethod

引數

無。

返回值

返回函式的類方法。

例項

以下例項展示了 classmethod 的使用方法:

#!/usr/bin/python

# -*- coding: UTF-8 -*-

 

class A(object):

    bar = 1

    def func1(self): 

        print ('foo')

    @classmethod

    def func2(cls):

        print ('func2')

        print (cls.bar)

        cls().func1()   # 呼叫 foo 方法

 

A.func2()               # 不需要例項化

 

輸出結果為:

func2

1

foo

 

compile() 函式

描述

compile() 函式將一個字串編譯為位元組程式碼。

語法

以下是 compile() 方法的語法:

compile(source, filename, mode[, flags[, dont_inherit]])

引數

source -- 字串或者AST(Abstract Syntax Trees)物件。。

filename -- 程式碼檔名稱,如果不是從檔案讀取程式碼則傳遞一些可辨認的值。

mode -- 指定編譯程式碼的種類。可以指定為 exec, eval, single。

flags -- 變數作用域,區域性名稱空間,如果被提供,可以是任何對映物件。。

flags和dont_inherit是用來控制編譯原始碼時的標誌

返回值

返回表示式執行結果。

例項

以下展示了使用 compile 函式的例項:

>>>str = "for i in range(0,10): print(i)"

>>> c = compile(str,'','exec')   # 編譯為位元組程式碼物件

>>> c

<code object <module> at 0x10141e0b0, file "", line 1>

>>> exec(c)

0

1

2

3

4

5

6

7

8

9

>>> str = "3 * 4 + 5"

>>> a = compile(str,'','eval')

>>> eval(a)

17

 

complex() 函式

描述

complex() 函式用於建立一個值為 real + imag * j 的複數或者轉化一個字串或數為複數。如果第一個引數為字串,則不需要指定第二個引數。。

語法

complex 語法:

class complex([real[, imag]])

引數說明:

real -- int, long, float或字串;

imag -- int, long, float;

返回值

返回一個複數。

例項

以下例項展示了 complex 的使用方法:

>>>complex(1, 2)

(1 + 2j)

 

>>> complex(1)    # 數字

(1 + 0j)

 

>>> complex("1")  # 當做字串處理

(1 + 0j)

 

# 注意:這個地方在"+"號兩邊不能有空格,也就是不能寫成"1 + 2j",應該是"1+2j",否則會報錯

>>> complex("1+2j")

(1 + 2j)

 

delattr() 函式

描述

delattr 函式用於刪除屬性。

delattr(x, 'foobar') 相等於 del x.foobar。

語法

delattr 語法:

delattr(object, name)

引數

object -- 物件。

name -- 必須是物件的屬性。

返回值

無。

例項

以下例項展示了 delattr 的使用方法:

#!/usr/bin/python

# -*- coding: UTF-8 -*-

 

class Coordinate:

    x = 10

    y = -5

    z = 0

 

point1 = Coordinate()

 

print('x = ',point1.x)

print('y = ',point1.y)

print('z = ',point1.z)

 

delattr(Coordinate, 'z')

 

print('--刪除 z 屬性後--')

print('x = ',point1.x)

print('y = ',point1.y)

 

# 觸發錯誤

print('z = ',point1.z)

輸出結果:

 

('x = ', 10)

('y = ', -5)

('z = ', 0)

--刪除 z 屬性後--

('x = ', 10)

('y = ', -5)

Traceback (most recent call last):

  File "test.py", line 22, in <module>

    print('z = ',point1.z)

AttributeError: Coordinate instance has no attribute 'z'

 

dict() 函式

字典函式,這裡就不多做解釋

 

dir() 函式

描述

dir() 函式不帶引數時,返回當前範圍內的變數、方法和定義的型別列表;帶引數時,返回引數的屬性、方法列表。如果引數包含方法__dir__(),該方法將被呼叫。如果引數不包含__dir__(),該方法將最大限度地收集引數資訊。

語法

dir 語法:

dir([object])

引數說明:

object -- 物件、變數、型別。

返回值

返回模組的屬性列表。

例項

以下例項展示了 dir 的使用方法:

>>>dir()   #  獲得當前模組的屬性列表

['__builtins__', '__doc__', '__name__', '__package__', 'arr', 'myslice']

>>> dir([ ])    # 檢視列表的方法

['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

>>> 

 

divmod() 函式

描述

Python divmod() 函式接收兩個數字型別(非複數)引數,返回一個包含商和餘數的元組(a // b, a % b)。

在 python 3.x 版本該函式不支援複數。

函式語法

divmod(a, b)

引數說明:

a: 數字,非複數。

b: 數字,非複數。

如果引數 a 與 引數 b 都是整數,函式返回的結果相當於 (a // b, a % b)

如果其中一個引數為浮點數時,函式返回的結果相當於 (q, a % b),q 通常是 math.floor(a / b),但也有可能是 1 ,比小,不過 q * b + a % b 的值會非常接近 a。

如果 a % b 的求餘結果不為 0 ,則餘數的正負符號跟引數 b 是一樣的,若 b 是正數,餘數為正數,若 b 為負數,餘數也為負數,並且 0 <= abs(a % b) < abs(b)。

例項

>>> divmod(7, 2)

(3, 1)

>>> divmod(8, 2)

(4, 0)

>>> divmod(8, -2)

(-4, 0)

>>> divmod(3, 1.3)

(2.0, 0.3999999999999999)

 

enumerate() 函式

描述

enumerate() 函式用於將一個可遍歷的資料物件(如列表、元組或字串)組合為一個索引序列,同時列出資料和資料下標,一般用在 for 迴圈當中。

語法

以下是 enumerate() 方法的語法:

enumerate(sequence, [start=0])

引數

sequence -- 一個序列、迭代器或其他支援迭代物件。

start -- 下標起始位置。

返回值

返回 enumerate(列舉) 物件。

例項

以下展示了使用 enumerate() 方法的例項:

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']

>>> list(enumerate(seasons))

[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]

>>> list(enumerate(seasons, start=1))       # 小標從 1 開始

[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

 

#普通的 for 迴圈

i = 0

seq = ['one', 'two', 'three']

for element in seq:

    print(i, seq[i])

    i += 1

 

輸出結果為:

0 one

1 two

2 three

 

 

#for 迴圈使用 enumerate

seq = ['one', 'two', 'three']

for i, element in enumerate(seq):

    print(i, element)

 

輸出結果為:

0 one

1 two

2 three

 

eval() 函式

描述

eval() 函式用來執行一個字串表示式,並返回表示式的值。

語法

以下是 eval() 方法的語法:

eval(expression[, globals[, locals]])

引數

expression -- 表示式。

globals -- 變數作用域,全域性名稱空間,如果被提供,則必須是一個字典物件。

locals -- 變數作用域,區域性名稱空間,如果被提供,可以是任何對映物件。

返回值

返回表示式計算結果。

例項

以下展示了使用 eval() 方法的例項:

>>>x = 7

>>> eval( '3 * x' )

21

>>> eval('pow(2,2)')

4

>>> eval('2 + 2')

4

>>> n=81

>>> eval("n + 4")

85

 

exec 函式

描述

exec 執行儲存在字串或檔案中的 Python 語句,相比於 eval,exec可以執行更復雜的 Python 程式碼。

語法

以下是 exec 的語法:

exec(object[, globals[, locals]])

引數

object:必選引數,表示需要被指定的 Python 程式碼。它必須是字串或 code 物件。如果 object 是一個字串,該字串會先被解析為一組 Python 語句,然後再執行(除非發生語法錯誤)。如果 object 是一個 code 物件,那麼它只是被簡單的執行。

globals:可選引數,表示全域性名稱空間(存放全域性變數),如果被提供,則必須是一個字典物件。

locals:可選引數,表示當前區域性名稱空間(存放區域性變數),如果被提供,可以是任何對映物件。如果該引數被忽略,那麼它將會取與 globals 相同的值。

返回值

exec 返回值永遠為 None。

例項

以下展示了使用 exec 的例項:

#例項 1

>>>exec('print("Hello World")')

Hello World

# 單行語句字串

>>> exec("print ('lizexiong.com')")

lizexiong.com

 

#  多行語句字串

>>> exec ("""for i in range(5):

...     print ("iter time: %d" % i)

... """)

iter time: 0

iter time: 1

iter time: 2

iter time: 3

iter time: 4

 

 

 

#例項 2

x = 10

expr = """

z = 30

sum = x + y + z

print(sum)

"""

def func():

    y = 20

    exec(expr)

    exec(expr, {'x': 1, 'y': 2})

    exec(expr, {'x': 1, 'y': 2}, {'y': 3, 'z': 4})

   

func()

 

filter() 函式

描述

filter() 函式用於過濾序列,過濾掉不符合條件的元素,返回一個迭代器物件,如果要轉換為列表,可以使用 list() 來轉換。

該接收兩個引數,第一個為函式,第二個為序列,序列的每個元素作為引數傳遞給函式進行判斷,然後返回 True 或 False,最後將返回 True 的元素放到新列表中。

語法

以下是 filter() 方法的語法:

filter(function, iterable)

引數

function -- 判斷函式。

iterable -- 可迭代物件。

返回值

返回一個迭代器物件

例項

以下展示了使用 filter 函式的例項:

#過濾出列表中的所有奇數:

#!/usr/bin/python3

 

def is_odd(n):

    return n % 2 == 1

 

tmplist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

newlist = list(tmplist)

print(newlist)

 

輸出結果 :

[1, 3, 5, 7, 9]

 

 

#過濾出1~100中平方根是整數的數:

#!/usr/bin/python3

 

import math

def is_sqr(x):

    return math.sqrt(x) % 1 == 0

 

tmplist = filter(is_sqr, range(1, 101))

newlist = list(tmplist)

print(newlist)

 

輸出結果 :

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

 

float() 函式

描述

float() 函式用於將整數和字串轉換成浮點數。

語法

float()方法語法:

class float([x])

引數

x -- 整數或字串

返回值

返回浮點數。

例項

以下例項展示了 float() 的使用方法:

>>>float(1)

1.0

>>> float(112)

112.0

>>> float(-123.6)

-123.6

>>> float('123')     # 字串

123.0

 

format 格式化函式

這個也做過很多次試驗,不做演示

 

frozenset() 函式

描述

frozenset() 返回一個凍結的集合,凍結後集合不能再新增或刪除任何元素。

語法

frozenset() 函式語法:

class frozenset([iterable])

引數

iterable -- 可迭代的物件,比如列表、字典、元組等等。

返回值

返回新的 frozenset 物件,如果不提供任何引數,預設會生成空集合。

例項

以下例項展示了 frozenset() 的使用方法:

>>>a = frozenset(range(10))     # 生成一個新的不可變集合

>>> a

frozenset([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

>>> b = frozenset('lizexiong')

>>> b

frozenset({'e', 'i', 'l', 'z', 'x', 'o', 'n', 'g'})   # 建立不可變集合

>>> 

為什麼需要凍結的集合(即不可變的集合)呢?因為在集合的關係中,有集合的中的元素是另一個集合的情況,但是普通集合(set)本身是可變的,那麼它的例項就不能放在另一個集合中(set中的元素必須是不可變型別)。

所以,frozenset提供了不可變的集合的功能,當集合不可變時,它就滿足了作為集合中的元素的要求,就可以放在另一個集合中了。

 

getattr() 函式

描述

getattr() 函式用於返回一個物件屬性值。

語法

getattr 語法:

getattr(object, name[, default])

引數

object -- 物件。

name -- 字串,物件屬性。

default -- 預設返回值,如果不提供該引數,在沒有對應屬性時,將觸發 AttributeError。

返回值

返回物件屬性值。

例項

以下例項展示了 getattr 的使用方法:

>>>class A(object):

...     bar = 1

...

>>> a = A()

>>> getattr(a, 'bar')        # 獲取屬性 bar 值

1

>>> getattr(a, 'bar2')       # 屬性 bar2 不存在,觸發異常

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

AttributeError: 'A' object has no attribute 'bar2'

>>> getattr(a, 'bar2', 3)    # 屬性 bar2 不存在,但設定了預設值

3

>>> 

 

 

獲取物件屬性後返回值可直接使用:

>>> class A(object):       

...     def set(self, a, b):

...         x = a       

...         a = b       

...         b = x       

...         print a, b  

...

>>> a = A()                

>>> c = getattr(a, 'set')

>>> c(a='1', b='2')

2 1

>>> 

 

globals() 函式

描述

globals() 函式會以字典型別返回當前位置的全部全域性變數。

語法

globals() 函式語法:

globals()

引數

返回值

返回全域性變數的字典。

例項

以下例項展示了 globals() 的使用方法:

>>> a='lizexiong'

>>> print (globals()) # globals 函式返回一個全域性變數的字典,包括所有匯入的變數。

{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <cl

ass '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {

}, '__builtins__': <module 'builtins' (built-in)>, 'a': 'lizexiong', 'b': frozen

set({'e', 'i', 'l', 'z', 'x', 'o', 'n', 'g'})}

>>> 

 

hasattr() 函式

描述

hasattr() 函式用於判斷物件是否包含對應的屬性。

語法

hasattr 語法:

hasattr(object, name)

引數

object -- 物件。

name -- 字串,屬性名。

返回值

如果物件有該屬性返回 True,否則返回 False。

例項

以下例項展示了 hasattr 的使用方法:

#!/usr/bin/python

# -*- coding: UTF-8 -*-

 

class Coordinate:

    x = 10

    y = -5

    z = 0

 

point1 = Coordinate()

print(hasattr(point1, 'x'))

print(hasattr(point1, 'y'))

print(hasattr(point1, 'z'))

print(hasattr(point1, 'no'))  # 沒有該屬性

 

輸出結果:

True

True

True

False

 

hash() 函式

描述

hash() 用於獲取取一個物件(字串或者數值等)的雜湊值。

語法

hash 語法:

hash(object)

引數說明:

object -- 物件;

返回值

返回物件的雜湊值。

例項

以下例項展示了 hash 的使用方法:

>>>hash('test')            # 字串

2314058222102390712

>>> hash(1)                 # 數字

1

>>> hash(str([1,2,3]))      # 集合

1335416675971793195

>>> hash(str(sorted({'1':1}))) # 字典

7666464346782421378

>>> 

 

hash() 函式可以應用於數字、字串和物件,不能直接應用於 list、set、dictionary。

在 hash() 對物件使用時,所得的結果不僅和物件的內容有關,還和物件的 id(),也就是記憶體地址有關。

 

class Test:

    def __init__(self, i):

        self.i = i

for i in range(10):

    t = Test(1)

    print(hash(t), id(t))

輸出結果:

 

(277855628, 4445690048)

(277855637, 4445690192)

(277855628, 4445690048)

(277855637, 4445690192)

(277855628, 4445690048)

(277855637, 4445690192)

(277855628, 4445690048)

(277855637, 4445690192)

(277855628, 4445690048)

(277855637, 4445690192)

 

help() 函式

描述

help() 函式用於檢視函式或模組用途的詳細說明。

語法

help 語法:

help([object])

引數說明:

object -- 物件;

返回值

返回物件幫助資訊。

例項

以下例項展示了 help 的使用方法:

>>>help('sys')             # 檢視 sys 模組的幫助

……顯示幫助資訊……

 

>>>help('str')             # 檢視 str 資料型別的幫助

……顯示幫助資訊……

 

>>>a = [1,2,3]

>>>help(a)                 # 檢視列表 list 幫助資訊

……顯示幫助資訊……

 

>>>help(a.append)          # 顯示list的append方法的幫助

……顯示幫助資訊……

 

hex() 函式

描述

hex() 函式用於將一個指定數字轉換為 16 進位制數。

語法

hex 語法:

hex(x)

引數說明:

x -- 一個整數

返回值

返回一個字串,以 0x 開頭。

例項

以下例項展示了 hex 的使用方法:

>>>hex(255)

'0xff'

>>> hex(-42)

'-0x2a'

>>> hex(12)

'0xc'

>>> type(hex(12))

<class 'str'>      # 字串

 

id() 函式

描述

id() 函式返回物件的唯一識別符號,識別符號是一個整數。

CPython 中 id() 函式用於獲取物件的記憶體地址。

語法

id 語法:

id([object])

引數說明:

object -- 物件。

返回值

返回物件的記憶體地址。

例項

以下例項展示了 id 的使用方法:

>>> a='lizexiong'

>>> id(a)

41491632

>>> b=1

>>> id(b)

8790933404736

 

input() 函式

接收使用者的輸入,這個接受一個標準輸入資料,返回為 string 型別。這個也不做過多解釋

 

int() 函式

描述

int() 函式用於將一個字串或數字轉換為整型。

語法

以下是 int() 方法的語法:

class int(x, base=10)

引數

x -- 字串或數字。

base -- 進位制數,預設十進位制。

返回值

返回整型資料。

>>>int()               # 不傳入引數時,得到結果0

0

>>> int(3)

3

>>> int(3.6)

3

>>> int('12',16)        # 如果是帶引數base的話,12要以字串的形式進行輸入,12 為 16進位制

18

>>> int('0xa',16) 

10 

>>> int('10',8) 

8

 

isinstance() 函式

描述

isinstance() 函式來判斷一個物件是否是一個已知的型別,類似 type()。

isinstance() 與 type() 區別:

l  type() 不會認為子類是一種父類型別,不考慮繼承關係。

l  isinstance() 會認為子類是一種父類型別,考慮繼承關係。

如果要判斷兩個型別是否相同推薦使用 isinstance()。

語法

以下是 isinstance() 方法的語法:

isinstance(object, classinfo)

引數

object -- 例項物件。

classinfo -- 可以是直接或間接類名、基本型別或者由它們組成的元組。

返回值

如果物件的型別與引數二的型別(classinfo)相同則返回 True,否則返回 False。

例項

以下展示了使用 isinstance 函式的例項:

>>>a = 2

>>> isinstance (a,int)

True

>>> isinstance (a,str)

False

>>> isinstance (a,(str,int,list))    # 是元組中的一個返回 True

True

type() 與 isinstance()區別:

class A:

    pass

 

class B(A):

    pass

 

isinstance(A(), A)    # returns True

type(A()) == A        # returns True

isinstance(B(), A)    # returns True

type(B()) == A        # returns False

 

issubclass() 函式

描述

issubclass() 方法用於判斷引數 class 是否是型別引數 classinfo 的子類。

語法

以下是 issubclass() 方法的語法:

issubclass(class, classinfo)

引數

class -- 類。

classinfo -- 類。

返回值

如果 class 是 classinfo 的子類返回 True,否則返回 False。

例項

以下展示了使用 issubclass 函式的例項:

#!/usr/bin/python

# -*- coding: UTF-8 -*-

 

class A:

    pass

class B(A):

    pass

   

print(issubclass(B,A))    # 返回 True

 

iter() 函式

描述

iter() 函式用來生成迭代器。

語法

以下是 iter() 方法的語法:

iter(object[, sentinel])

引數

object -- 支援迭代的集合物件。

sentinel -- 如果傳遞了第二個引數,則引數 object 必須是一個可呼叫的物件(如,函式),此時,iter 建立了一個迭代器物件,每次呼叫這個迭代器物件的__next__()方法時,都會呼叫 object。

開啟模式

返回值

迭代器物件。

例項

>>>lst = [1, 2, 3]

>>> for i in iter(lst):

...     print(i)

...

1

2

3

 

len()方法

描述

Python len() 方法返回物件(字元、列表、元組等)長度或專案個數。

語法

len()方法語法:

len( s )

引數

s -- 物件。

返回值

返回物件長度。

例項

以下例項展示了 len() 的使用方法:

>>> str="lizexiong"

>>> len(str)

9

>>> l = [1,2,3,4,5]

>>> len(l)

5

>>> dic={'k1':'v1'}

>>> len(dic)

1

 

list()方法

描述

list() 方法用於將元組或字串轉換為列表。

注:元組與列表是非常類似的,區別在於元組的元素值不能修改,元組是放在括號中,列表是放於方括號中。

語法

list()方法語法:

list( seq )

引數

seq -- 要轉換為列表的元組或字串。

返回值

返回列表。

例項

以下例項展示了 list()函式的使用方法:

#!/usr/bin/python3

 

aTuple = (123, 'Google', 'lizexiong', 'Taobao')

list1 = list(aTuple)

print ("列表元素 : ", list1)

 

str="Hello World"

list2=list(str)

print ("列表元素 : ", list2)

 

以上例項輸出結果如下:

列表元素 :  [123, 'Google', 'lizexiong', 'Taobao']

列表元素 :  ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']

 

locals() 函式

描述

locals() 函式會以字典型別返回當前位置的全部區域性變數。

對於函式, 方法, lambda 函式, 類, 以及實現了 __call__ 方法的類例項, 它都返回 True。

語法

locals() 函式語法:

locals()

引數

返回值

返回字典型別的區域性變數。

例項

以下例項展示了 locals() 的使用方法:

>>>def lizexiong(arg):    # 兩個區域性變數:arg、z

...     z = 1

...     print (locals())

...

>>> lizexiong(5)

{'z': 1, 'arg': 5}      # 返回一個名字/值對的字典

>>> 

 

map() 函式

描述

map() 函式會根據提供的函式對指定序列做對映。

第一個引數 function 以引數序列中的每一個元素呼叫 function 函式,返回包含每次 function 函式返回值的新列表。

語法

以下是 map() 方法的語法:

map(function, iterable, ...)

引數

function -- 函式

iterable -- 一個或多個序列

返回值

返回一個迭代器。

例項

以下例項展示了 map() 的使用方法:

>>> def square(x) :         # 計算平方數

...     return x ** 2

...

>>> map(square, [1,2,3,4,5])    # 計算列表各個元素的平方

<map object at 0x100d3d550>     # 返回迭代器

>>> list(map(square, [1,2,3,4,5]))   # 使用 list() 轉換為列表

[1, 4, 9, 16, 25]

>>> list(map(lambda x: x ** 2, [1, 2, 3, 4, 5]))   # 使用 lambda 匿名函式

[1, 4, 9, 16, 25]

>>> 

 

max() 函式

描述

max() 方法返回給定引數的最大值,引數可以為序列。

語法

以下是 max() 方法的語法:

max( x, y, z, .... )

引數

x -- 數值表示式。

y -- 數值表示式。

z -- 數值表示式。

返回值

返回給定引數的最大值。

例項

以下展示了使用 max() 方法的例項:

#!/usr/bin/python3

 

print ("max(80, 100, 1000) : ", max(80, 100, 1000))

print ("max(-20, 100, 400) : ", max(-20, 100, 400))

print ("max(-80, -20, -10) : ", max(-80, -20, -10))

print ("max(0, 100, -400) : ", max(0, 100, -400))

 

以上例項執行後輸出結果為:

max(80, 100, 1000) :  1000

max(-20, 100, 400) :  400

max(-80, -20, -10) :  -10

max(0, 100, -400) :  100

 

memoryview() 函式

描述

memoryview() 函式返回給定引數的記憶體檢視物件(memory view)。

所謂記憶體檢視物件,是指對支援緩衝區協議的資料進行包裝,在不需要複製物件基礎上允許Python程式碼訪問。

語法

memoryview 語法:

memoryview(obj)

引數說明:

obj -- 物件

返回值

返回元組列表。

例項

以下例項展示了 memoryview 的使用方法:

#Python2.x 應用:

>>>v = memoryview('abcefg')

>>> v[1]

'b'

>>> v[-1]

'g'

>>> v[1:4]

<memory at 0x77ab28>

>>> v[1:4].tobytes()

'bce'

 

 

#Python3.x 應用:

>>>v = memoryview(bytearray("abcefg", 'utf-8'))

>>> print(v[1])

98

>>> print(v[-1])

103

>>> print(v[1:4])

<memory at 0x10f543a08>

>>> print(v[1:4].tobytes())

b'bce'

>>> 

 

min() 函式

描述

min() 方法返回給定引數的最小值,引數可以為序列。

語法

以下是 min() 方法的語法:

min( x, y, z, .... )

引數

x -- 數值表示式。

y -- 數值表示式。

z -- 數值表示式。

返回值

返回給定引數的最小值。

例項

以下展示了使用 min() 方法的例項:

#!/usr/bin/python3

 

print ("min(80, 100, 1000) : ", min(80, 100, 1000))

print ("min(-20, 100, 400) : ", min(-20, 100, 400))

print ("min(-80, -20, -10) : ", min(-80, -20, -10))

print ("min(0, 100, -400) : ", min(0, 100, -400))

 

以上例項執行後輸出結果為:

min(80, 100, 1000) :  80

min(-20, 100, 400) :  -20

min(-80, -20, -10) :  -80

min(0, 100, -400) :  -400

 

next() 函式

描述

next() 返回迭代器的下一個專案。

next() 函式要和生成迭代器的 iter() 函式一起使用。

語法

next 語法:

next(iterable[, default])

引數說明:

iterable -- 可迭代物件

default -- 可選,用於設定在沒有下一個元素時返回該預設值,如果不設定,又沒有下一個元素則會觸發 StopIteration 異常。

返回值

返回下一個專案。

例項

以下例項展示了 next 的使用方法:

#!/usr/bin/python

# -*- coding: UTF-8 -*-

 

# 首先獲得Iterator物件:

it = iter([1, 2, 3, 4, 5])

# 迴圈:

while True:

    try:

        # 獲得下一個值:

        x = next(it)

        print(x)

    except StopIteration:

        # 遇到StopIteration就退出迴圈

        break

 

輸出結果為:

1

2

3

4

5

 

 

#如果傳入第二個引數, 獲取最後一個元素之後, 下一次next返回該預設值, 而不會丟擲 StopIteration:

 

#!/usr/bin/python

# -*- coding: UTF-8 -*-

 

it = iter([1, 2, 5, 4, 3])

while True:

    x = next(it, 'a')

    print(x)

    if x == 'a':

        break

輸入結果為:

 

1

2

5

4

3

a

 

oct() 函式

描述

oct() 函式將一個整數轉換成 8 進位制字串,8 進位制以 0o 作為字首表示。

語法

oct 語法:

oct(x)

引數說明:

x -- 整數。

返回值

返回 8 進位制字串。

例項

以下例項展示了 oct 的使用方法:

>>> oct(10)

'0o12'

>>> oct(20)

'0o24'

>>> oct(15)

'0o17'

 

open() 函式

檔案操作,這裡也不多說

 

ord() 函式

描述

ord() 函式是 chr() 函式(對於 8 位的 ASCII 字串)的配對函式,它以一個字串(Unicode 字元)作為引數,返回對應的 ASCII 數值,或者 Unicode 數值。

語法

以下是 ord() 方法的語法:

ord(c)

引數

c -- 字元。

返回值

返回值是對應的十進位制整數。

例項

以下展示了使用 ord() 方法的例項:

>>>ord('a')

97

>>> ord('€')

8364

>>> 

 

pow() 函式

描述

pow() 方法返回 xy(x的y次方) 的值。

語法

以下是 math 模組 pow() 方法的語法:

import math

 

math.pow( x, y )

內建的 pow() 方法

pow(x, y[, z])

函式是計算x的y次方,如果z在存在,則再對結果進行取模,其結果等效於pow(x,y) %z

注意:pow() 通過內建的方法直接呼叫,內建方法會把引數作為整型,而 math 模組則會把引數轉換為 float。

引數

x -- 數值表示式。

y -- 數值表示式。

z -- 數值表示式。

返回值

返回 xy(x的y次方) 的值。

例項

以下展示了使用 pow() 方法的例項:

#!/usr/bin/python3

import math   # 匯入 math 模組

 

print ("math.pow(100, 2) : ", math.pow(100, 2))

# 使用內建,檢視輸出結果區別

print ("pow(100, 2) : ", pow(100, 2))

print ("math.pow(100, -2) : ", math.pow(100, -2))

print ("math.pow(2, 4) : ", math.pow(2, 4))

print ("math.pow(3, 0) : ", math.pow(3, 0))

 

以上例項執行後輸出結果為:

math.pow(100, 2) :  10000.0

pow(100, 2) :  10000

math.pow(100, -2) :  0.0001

math.pow(2, 4) :  16.0

math.pow(3, 0) :  1.0

 

print()函式

print() 方法用於列印輸出,最常見的一個函式。

在 Python3.3 版增加了 flush 關鍵字引數。

print 在 Python3.x 是一個函式,但在 Python2.x 版本不是一個函式,只是一個關鍵字。

這裡不做過多介紹

 

property() 函式

描述

property() 函式的作用是在新式類中返回屬性值。

語法

以下是 property() 方法的語法:

class property([fget[, fset[, fdel[, doc]]]])

引數

fget -- 獲取屬性值的函式

fset -- 設定屬性值的函式

fdel -- 刪除屬性值函式

doc -- 屬性描述資訊

返回值

返回新式類屬性。

例項

class C(object):

    def __init__(self):

        self._x = None

 

    def getx(self):

        return self._x

 

    def setx(self, value):

        self._x = value

 

    def delx(self):

        del self._x

 

    x = property(getx, setx, delx, "I'm the 'x' property.")

如果 c 是 C 的例項化, c.x 將觸發 getter,c.x = value 將觸發 setter , del c.x 觸發 deleter。

如果給定 doc 引數,其將成為這個屬性值的 docstring,否則 property 函式就會複製 fget 函式的 docstring(如果有的話)。

將 property 函式用作裝飾器可以很方便的建立只讀屬性:

class Parrot(object):

    def __init__(self):

        self._voltage = 100000

 

    @property

    def voltage(self):

        """Get the current voltage."""

        return self._voltage

上面的程式碼將 voltage() 方法轉化成同名只讀屬性的 getter 方法。

property 的 getter,setter 和 deleter 方法同樣可以用作裝飾器:

class C(object):

    def __init__(self):

        self._x = None

 

    @property

    def x(self):

        """I'm the 'x' property."""

        return self._x

 

    @x.setter

    def x(self, value):

        self._x = value

 

    @x.deleter

    def x(self):

        del self._x

這個程式碼和第一個例子完全相同,但要注意這些額外函式的名字和 property 下的一樣,例如這裡的 x。

 

range() 函式用法

Python3 range() 函式返回的是一個可迭代物件(型別是物件),而不是列表型別, 所以列印的時候不會列印列表。

Python3 list() 函式是物件迭代器,可以把range()返回的可迭代物件轉為一個列表,返回的變數型別為列表。

Python2 range() 函式返回的是列表。

函式語法

range(stop)

range(start, stop[, step])

引數說明:

start: 計數從 start 開始。預設是從 0 開始。例如range(5)等價於range(0, 5);

stop: 計數到 stop 結束,但不包括 stop。例如:range(0, 5) 是[0, 1, 2, 3, 4]沒有5

step:步長,預設為1。例如:range(0, 5) 等價於 range(0, 5, 1)

例項

>>>range(5)

range(0, 5)

>>> for i in range(5):

...     print(i)

...

0

1

2

3

4

>>> list(range(5))

[0, 1, 2, 3, 4]

>>> list(range(0))

[]

>>> 

 

有兩個引數或三個引數的情況(第二種構造方法)::

>>>list(range(0, 30, 5))

[0, 5, 10, 15, 20, 25]

>>> list(range(0, 10, 2))

[0, 2, 4, 6, 8]

>>> list(range(0, -10, -1))

[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]

>>> list(range(1, 0))

[]

>>> 

>>> 

 

repr() 函式

描述

repr() 函式將物件轉化為供直譯器讀取的形式。

語法

以下是 repr() 方法的語法:

repr(object)

引數

object -- 物件。

返回值

返回一個物件的 string 格式。

例項

以下展示了使用 repr() 方法的例項:

>>> s = 'LIZEXIONG'

>>> repr(s)

"'LIZEXIONG'"

>>> dict = {'lizexiong': 'lizexiong.com', 'google': 'google.com'};

>>> repr(dict)

"{'google': 'google.com', 'lizexiong': 'lizexiong.com'}"

>>> 

 

#repr() 方法可以將讀取到的格式字元,比如換行符、製表符,轉化為其相應的轉義字元。

示例:

# coding=UTF-8

s="物品\t單價\t數量\n包子\t1\t2"

print(s)

print(repr(s))

 

執行結果:

物品    單價    數量

包子    1       2  

'物品\t單價\t數量\n包子\t1\t2'

 

reversed 函式

描述

reversed 函式返回一個反轉的迭代器。

語法

以下是 reversed 的語法:

reversed(seq)

引數

seq -- 要轉換的序列,可以是 tuple, string, list 或 range。

返回值

返回一個反轉的迭代器。

例項

以下展示了使用 tuple 的例項:

#!/usr/bin/env python3

 

# 字串

seqString = 'lizexiong'

print(list(reversed(seqString)))

 

# 元組

seqTuple = ('L', 'i', 'z', 'e', 'x', 'i','o','n','g')

print(list(reversed(seqTuple)))

 

# range

seqRange = range(5, 9)

print(list(reversed(seqRange)))

 

# 列表

seqList = [1, 2, 4, 3, 5]

print(list(reversed(seqList)))

 

以上例項輸出結果為:

['g', 'n', 'o', 'i', 'x', 'e', 'z', 'i', 'L']

['g', 'n', 'o', 'i', 'x', 'e', 'z', 'i', 'L']

[8, 7, 6, 5]

[5, 3, 4, 2, 1]

 

round() 函式

描述

round()方法返回浮點數 x 的四捨五入值,準確的說保留值將保留到離上一位更近的一端(四捨六入)。

精度要求高的,不建議使用該函式。

語法

以下是 round() 方法的語法:

round( x [, n]  )

引數

x -- 數字表達式。

n -- 表示從小數點位數,其中 x 需要四捨五入,預設值為 0。

返回值

返回浮點數x的四捨五入值。

例項

以下展示了使用 round() 方法的例項:

#!/usr/bin/python3

 

print ("round(70.23456) : ", round(70.23456))

print ("round(56.659,1) : ", round(56.659,1))

print ("round(80.264, 2) : ", round(80.264, 2))

print ("round(100.000056, 3) : ", round(100.000056, 3))

print ("round(-100.000056, 3) : ", round(-100.000056, 3))

 

以上例項執行後輸出結果為:

round(70.23456) :  70

round(56.659,1) :  56.7

round(80.264, 2) :  80.26

round(100.000056, 3) :  100.0

round(-100.000056, 3) :  -100.0

 

看下官網給的一個例子:

>>> round(2.675, 2)

2.67

按我們的想法返回結果應該是 2.68,可結果卻是 2.67,為什麼?

這跟浮點數的精度有關。我們知道在機器中浮點數不一定能精確表達,因為換算成一串 1 和 0 後可能是無限位數的,機器已經做出了截斷處理。那麼在機器中儲存的2.675這個數字就比實際數字要小那麼一點點。這一點點就導致了它離 2.67 要更近一點點,所以保留兩位小數時就近似到了 2.67。

 

set() 函式

描述

set() 函式建立一個無序不重複元素集,可進行關係測試,刪除重複資料,還可以計算交集、差集、並集等。

語法

set 語法:

class set([iterable])

引數說明:

iterable -- 可迭代物件物件;

返回值

返回新的集合物件。

例項

以下例項展示了 set 的使用方法:

>>> x = set('lizexiong')

>>> y = set('google')

>>> x,y

({'n', 'o', 'e', 'i', 'x', 'l', 'g', 'z'}, {'o', 'g', 'l', 'e'})  #重複的被刪除

>>> x & y                           #交集

{'o', 'g', 'l', 'e'}

>>> x | y                           #並集

{'n', 'o', 'e', 'i', 'x', 'l', 'g', 'z'}

>>> x - y                           #差集

{'x', 'z', 'i', 'n'}

 

setattr() 函式

描述

setattr() 函式對應函式 getattr(),用於設定屬性值,該屬性不一定是存在的。

語法

setattr() 語法:

setattr(object, name, value)

引數

object -- 物件。

name -- 字串,物件屬性。

value -- 屬性值。

返回值

無。

例項

以下例項展示了 setattr() 函式的使用方法:

對已存在的屬性進行賦值:

>>>class A(object):

...     bar = 1

...

>>> a = A()

>>> getattr(a, 'bar')          # 獲取屬性 bar 值

1

>>> setattr(a, 'bar', 5)       # 設定屬性 bar 值

>>> a.bar

5

如果屬性不存在會建立一個新的物件屬性,並對屬性賦值:

 

>>>class A():

...     name = "lizexiong"

...

>>> a = A()

>>> setattr(a, "age", 28)

>>> print(a.age)

28

>>> 

 

slice() 函式

描述

slice() 函式實現切片物件,主要用在切片操作函式裡的引數傳遞。

語法

slice 語法:

class slice(stop)

class slice(start, stop[, step])

引數說明:

start -- 起始位置

stop -- 結束位置

step -- 間距

返回值

返回一個切片物件。

例項

以下例項展示了 slice 的使用方法:

>>>myslice = slice(5)    # 設定擷取5個元素的切片

>>> myslice

slice(None, 5, None)

>>> arr = range(10)

>>> arr

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> arr[myslice]         # 擷取 5 個元素

[0, 1, 2, 3, 4]

>>> 

 

sorted() 函式

描述

sorted() 函式對所有可迭代的物件進行排序操作。

sort 與 sorted 區別:

sort 是應用在 list 上的方法,sorted 可以對所有可迭代的物件進行排序操作。

list 的 sort 方法返回的是對已經存在的列表進行操作,而內建函式 sorted 方法返回的是一個新的 list,而不是在原來的基礎上進行的操作。

語法

sorted 語法:

sorted(iterable, key=None, reverse=False) 

引數說明:

iterable -- 可迭代物件。

key -- 主要是用來進行比較的元素,只有一個引數,具體的函式的引數就是取自於可迭代物件中,指定可迭代物件中的一個元素來進行排序。

reverse -- 排序規則,reverse = True 降序 , reverse = False 升序(預設)。

返回值

返回重新排序的列表。

例項

以下例項展示了 sorted 的最簡單的使用方法:

>>> sorted([5, 2, 3, 1, 4])

[1, 2, 3, 4, 5]                      # 預設為升序

你也可以使用 list 的 list.sort() 方法。這個方法會修改原始的 list(返回值為None)。通常這個方法不如sorted()方便-如果你不需要原始的 list,list.sort()方法效率會稍微高一些。

>>> a=[5,2,3,1,4]

>>> a.sort()

>>> a

[1,2,3,4,5]

另一個區別在於list.sort() 方法只為 list 定義。而 sorted() 函式可以接收任何的 iterable。

>>> sorted({1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'})

[1, 2, 3, 4, 5]

利用key進行倒序排序

>>> example_list = [5, 0, 6, 1, 2, 7, 3, 4]

>>> result_list = sorted(example_list, key=lambda x: x*-1)

>>> print(result_list)

[7, 6, 5, 4, 3, 2, 1, 0]

>>> 

要進行反向排序,也通過傳入第三個引數 reverse=True:

>>> example_list = [5, 0, 6, 1, 2, 7, 3, 4]

>>> sorted(example_list, reverse=True)

[7, 6, 5, 4, 3, 2, 1, 0]

以下是個更復雜的例項,對獎牌榜就行排序,資料裡面包含了15個國家的金、銀、銅資料,使用 \n 作為分隔符:

s = "德國 10 11 16\n義大利 10 10 20\n荷蘭 10 12 14\n法國 10 12 11\n英國 22 21 22\n中國 38 32 18\n日本 27 14 17\n美國 39 41 33\n俄羅斯奧委會 20 28 23\n澳大利亞 17 7 22\n匈牙利 6 7 7\n加拿大 7 6 11\n古巴 7 3 5\n巴西 7 6 8\n紐西蘭 7 6 7"

stodata = s.split('\n',-1)

 

# 使用sorted

para = {}

 

for line in range(len(stodata)):

    # 每一行資料

    data = stodata[line].split(' ')

    print(data)

    # 組裝資料結構para={'China': [], 'Russia': []}

    para[data[0]] = [int('-' + i) for i in data[1:]]

# 開始排序(x[1]代表獎牌數目, x[0]代表國家)

new_para = sorted(para.items(), key=lambda x: (x[1], x[0]))

print()

 

c=[]

for i in new_para:

     c.append((i[0]))

for j in range(15):

    print(f"{(j+1):2d}  {c[j]}")

 

輸出結果為:

['德國', '10', '11', '16']

['義大利', '10', '10', '20']

['荷蘭', '10', '12', '14']

['法國', '10', '12', '11']

['英國', '22', '21', '22']

['中國', '38', '32', '18']

['日本', '27', '14', '17']

['美國', '39', '41', '33']

['俄羅斯奧委會', '20', '28', '23']

['澳大利亞', '17', '7', '22']

['匈牙利', '6', '7', '7']

['加拿大', '7', '6', '11']

['古巴', '7', '3', '5']

['巴西', '7', '6', '8']

['紐西蘭', '7', '6', '7']

 

 1  美國

 2  中國

 3  日本

 4  英國

 5  俄羅斯奧委會

 6  澳大利亞

 7  荷蘭

 8  法國

 9  德國

10  義大利

11  加拿大

12  巴西

13  紐西蘭

14  古巴

15  匈牙利

 

sorted 的應用,也可以通過 key 的值來進行陣列/字典的排序,比如:

 

array = [{"age":20,"name":"a"},{"age":25,"name":"b"},{"age":10,"name":"c"}]

array = sorted(array,key=lambda x:x["age"])

print(array)

輸出結果:

 

[{'age': 10, 'name': 'c'}, {'age': 20, 'name': 'a'}, {'age': 25, 'name': 'b'}]

 

staticmethod() 函式

python staticmethod 返回函式的靜態方法。

該方法不強制要求傳遞引數,如下宣告一個靜態方法:

class C(object):

    @staticmethod

    def f(arg1, arg2, ...):

        ...

以上例項聲明瞭靜態方法 f,從而可以實現例項化使用 C().f(),當然也可以不例項化呼叫該方法 C.f()。

函式語法

staticmethod(function)

引數說明:

例項

#!/usr/bin/python

# -*- coding: UTF-8 -*-

 

class C(object):

    @staticmethod

    def f():

        print('lizexiong');

 

C.f();          # 靜態方法無需例項化

cobj = C()

cobj.f()        # 也可以例項化後呼叫

以上例項輸出結果為:

 

lizexiong

lizexiong

 

str() 函式

描述

str() 函式將物件轉化為適於人閱讀的形式。

語法

以下是 str() 方法的語法:

class str(object='')

引數

object -- 物件。

返回值

返回一個物件的string格式。

例項

以下展示了使用 str() 方法的例項:

>>>s = 'LIZEXIONG'

>>> str(s)

'LIZEXIONG'

>>> dict = {'lizexiong': 'lizexiong.com', 'google': 'google.com'};

>>> str(dict)

"{'google': 'google.com', 'lizexiong': 'lizexiong.com'}"

>>> 

 

sum() 函式

描述

sum() 方法對序列進行求和計算。

語法

以下是 sum() 方法的語法:

sum(iterable[, start])

引數

iterable -- 可迭代物件,如:列表、元組、集合。

start -- 指定相加的引數,如果沒有設定這個值,預設為0。

返回值

返回計算結果。

例項

以下展示了使用 sum 函式的例項:

>>>sum([0,1,2]) 

>>> sum((2, 3, 4), 1)        # 元組計算總和後再加 1

10

>>> sum([0,1,2,3,4], 2)      # 列表計算總和後再加 2

12

 

super() 函式

描述

super() 函式是用於呼叫父類(超類)的一個方法。

super() 是用來解決多重繼承問題的,直接用類名呼叫父類方法在使用單繼承的時候沒問題,但是如果使用多繼承,會涉及到查詢順序(MRO)、重複呼叫(鑽石繼承)等種種問題。

MRO 就是類的方法解析順序表, 其實也就是繼承父類方法時的順序表。

語法

以下是 super() 方法的語法:

super(type[, object-or-type])

引數

type -- 類。

object-or-type -- 類,一般是 self

Python3.x 和 Python2.x 的一個區別是: Python 3 可以使用直接使用 super().xxx 代替 super(Class, self).xxx :

Python3.x 例項:

class A:

     def add(self, x):

         y = x+1

         print(y)

class B(A):

    def add(self, x):

        super().add(x)

b = B()

b.add(2)  # 3

 

Python2.x 例項:

#!/usr/bin/python

# -*- coding: UTF-8 -*-

 

class A(object):   # Python2.x 記得繼承 object

    def add(self, x):

         y = x+1

         print(y)

class B(A):

    def add(self, x):

        super(B, self).add(x)

b = B()

b.add(2)  # 3

返回值

無。

例項

以下展示了使用 super 函式的例項:

#!/usr/bin/python

# -*- coding: UTF-8 -*-

 

class FooParent(object):

    def __init__(self):

        self.parent = 'I\'m the parent.'

        print ('Parent')

   

    def bar(self,message):

        print ("%s from Parent" % message)

 

class FooChild(FooParent):

    def __init__(self):

        # super(FooChild,self) 首先找到 FooChild 的父類(就是類 FooParent),然後把類 FooChild 的物件轉換為類 FooParent 的物件

        super(FooChild,self).__init__()   

        print ('Child')

       

    def bar(self,message):

        super(FooChild, self).bar(message)

        print ('Child bar fuction')

        print (self.parent)

 

if __name__ == '__main__':

    fooChild = FooChild()

    fooChild.bar('HelloWorld')

 

 

執行結果:

Parent

Child

HelloWorld from Parent

Child bar fuction

I'm the parent.

 

tuple 函式

描述

tuple 函式將可迭代系列(如列表)轉換為元組。

語法

以下是 tuple 的語法:

tuple( iterable )

引數

iterable -- 要轉換為元組的可迭代序列。

返回值

返回元組。

例項

以下展示了使用 tuple 的例項:

>>>list1= ['Google', 'Taobao', 'lizexiong', 'Baidu']

>>> tuple1=tuple(list1)

>>> tuple1

('Google', 'Taobao', 'lizexiong', 'Baidu')

 

type()

這個用法也比較簡單,略過了

 

vars() 函式

描述

vars() 函式返回物件object的屬性和屬性值的字典物件。

語法

vars() 函式語法:

vars([object])

引數

object -- 物件

返回值

返回物件object的屬性和屬性值的字典物件,如果沒有引數,就列印當前呼叫位置的屬性和屬性值 類似 locals()。

例項

以下例項展示了 vars() 的使用方法:

>>> print (vars())

{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <cl

ass '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {

}, '__builtins__': <module 'builtins' (built-in)>}

>>> class Test:

...   a=1

...

>>> print (vars(Test))

{'__module__': '__main__', 'a': 1, '__dict__': <attribute '__dict__' of 'Test' o

bjects>, '__weakref__': <attribute '__weakref__' of 'Test' objects>, '__doc__':

None}

>>> test = Test()

>>> print (vars(test))

{}

vars 的一個用法是動態生成類成員。

# 來自 Python 官方文件 enum 模組的例子

from datetime import timedelta

from enum import Enum

class Period(timedelta, Enum):

    "different lengths of time"

    _ignore_ = 'Period i'

    Period = vars()

    for i in range(367):

        Period['day_%d' % i] = i

 

print(Period.day_5.value)

# 5 days, 0:00:00

這裡的 vars 表示的是類定義內部的區域性作用域,相當於分別執行下面這些程式碼:

 

class Period(timedelta, Enum):

    "different lengths of time"

    day_1 = timedelta(1)

    day_2 = timedelta(2)

    ...

    day_366 = timedelta(366)

由於類定義內部是單獨的作用域,因此用 globals 或者 locals 達不到相同的效果,而在類定義中,因為類名稱還不可用,因此也無法用 setattr 實現。

 

zip() 函式

描述

zip() 函式用於將可迭代的物件作為引數,將物件中對應的元素打包成一個個元組,然後返回由這些元組組成的物件,這樣做的好處是節約了不少的記憶體。

我們可以使用 list() 轉換來輸出列表。

如果各個迭代器的元素個數不一致,則返回列表長度與最短的物件相同,利用 * 號操作符,可以將元組解壓為列表。

zip 方法在 Python 2 和 Python 3 中的不同:在 Python 2.x zip() 返回的是一個列表。

語法

zip 語法:

zip([iterable, ...])

引數說明:

iterabl -- 一個或多個迭代器;

返回值

返回一個物件。

例項

以下例項展示了 zip 的使用方法:

>>> a = [1,2,3]

>>> b = [4,5,6]

>>> c = [4,5,6,7,8]

>>> zipped = zip(a,b)     # 返回一個物件

>>> zipped

<zip object at 0x103abc288>

>>> list(zipped)  # list() 轉換為列表

[(1, 4), (2, 5), (3, 6)]

>>> list(zip(a,c))              # 元素個數與最短的列表一致

[(1, 4), (2, 5), (3, 6)]

 

>>> a1, a2 = zip(*zip(a,b))          # 與 zip 相反,zip(*) 可理解為解壓,返回二維矩陣式

>>> list(a1)

[1, 2, 3]

>>> list(a2)

[4, 5, 6]

>>> 

 

__import__() 函式

描述

__import__() 函式用於動態載入類和函式 。

如果一個模組經常變化就可以使用 __import__() 來動態載入。

語法

__import__ 語法:

__import__(name[, globals[, locals[, fromlist[, level]]]])

引數說明:

name -- 模組名

返回值

返回元組列表。

例項

以下例項展示了 __import__ 的使用方法:

#a.py 檔案程式碼:

#!/usr/bin/env python   

#encoding: utf-8 

 

import os 

print ('在 a.py 檔案中 %s' % id(os))

 

#test.py 檔案程式碼:

#!/usr/bin/env python   

#encoding: utf-8 

 

import sys 

__import__('a')        # 匯入 a.py 模組

 

 

執行 test.py 檔案,輸出結果為:

在 a.py 檔案中 4394716136

 

reload() 函式

描述

reload() 用於重新載入之前載入的模組。

在 Python2.x 版本中 reload() 是內建函式,可以直線使用。在 Python2.x ~ Python3.3 版本移到 imp 包中(Python2.x 也可以匯入 imp 包使用),Python3.4 之後到版本移到了 importlib 包中。

語法

Python2.x ~ Python3.3 之前版本:

import imp

imp.reload(module)

from imp import reload

reload(module)

Python3.4 之後到版本:

import importlib

importlib.reload(module)

from importlib import reload

reload(module)

引數

module -- 模組物件。

返回值

返回模組物件。

例項

以下例項展示了 reload() 的使用方法。

例項 1

重新載入 sys 模組

>>> import sys, importlib

>>> importlib.reload(sys)

<module 'sys' (built-in)>

例項 2

首先我們在當前目錄下建立一個 lizexiong.py :

lizexiong.py 檔案

# lizexiong.py 檔案測試程式碼

site = "LIZEXIONG"

在當前目錄下啟動 Python 互動式命令視窗:

>>>import lizexiong

>>> lizexiong.site

'LIZEXIONG'

然後在另外一個視窗編輯 lizexiong.py 檔案(不要關閉以上的 Python 互動式命令視窗),修改為以下程式碼:

修改後的 lizexiong.py 檔案

# lizexiong.py 檔案測試程式碼

site = "GOOGLE"

然後回到 Python 互動式命令視窗:

>>> lizexiong.site    # 輸出結果沒有變化

'LIZEXIONG'

>>> from importlib import reload  # Python 3.4+

>>> reload(lizexiong)    # 重新載入修改後的 lizexiong.py 檔案

<module 'lizexiong' from '/Users/lizexiong/lizexiong-test/lizexiong.py'>

>>> lizexiong.site    # 輸出結果正常了

'GOOGLE'