1. 程式人生 > >Python中的一些內建函式

Python中的一些內建函式

  Python中有許多強大的內建函式,通過這些函式可以很方便的完成一項功能。如果能夠熟練的運用能夠在編碼的時候幫上大忙。當然內建函式不止下面這些,後面會逐漸補充學習。

1. eval(source[, globals[, locals]])

執行一個字串表示式,並返回執行的結果(可以理解為去掉引號後python程式碼):

>>> x = 10
>>> y = 5
>>> eval('x+y')
15
>>> eval('[1,2,3,4]')
[1, 2, 3, 4]
>>> eval('123'
) 123

2. filter(function or None, sequence) -> list, tuple, or string

filter用來提取系列中滿足function函式的元素,
當第一個引數為None是,則判斷條件為系列中的每隔元素是否為False(在Python中None, ”, 0表示False)
下面是計算10以內的偶數:

>>> filter(lambda x : x % 2 == 0, range(10))
[0, 2, 4, 6, 8]

函式為None時, 只是將0過濾了:

>>> filter(None
, range(10)) [1, 2, 3, 4, 5, 6, 7, 8, 9]

3. enumerate(iterable[, start]) -> iterator for index, value of iterable

用enumerate返回下面的結構,

(0, seq[0]), (1, seq[1]), (2, seq[2]), ...

因此可以很方便的遍歷一個可迭代的物件,並且知道其索引,start為索引的開始值。下面用enumerate方法打印出字串的每個字母及其索引:

>>> for index, c in enumerate('hello world'
): print index, c 0 h 1 e 2 l 3 l 4 o 5 6 w 7 o 8 r 9 l 10 d

start為10:

>>> for index, c in enumerate('hello world', 10):
    print index, c

10 h
11 e
12 l
13 l
14 o
15  
16 w
17 o
18 r
19 l
20 d

4. map(function, sequence[, sequence, …]) -> list

又一個強大好用的內建函式,下面的function為空時候的例子,但是後面的系列不能為None,否則丟擲異常

>>> map(None, 'hello', (1,2,3), [5,6,7,8])
[('h', 1, 5), ('e', 2, 6), ('l', 3, 7), ('l', None, 8), ('o', None, None)]

  由此可見當後面有多個序列,並且長度不一致時,按照最長的系列來生成元組,其它長度不夠的用None補足。實際上第一個引數就是用來處理生成的系列中的元組的,把處理的結果作為元素組成一個列表返回。
  根據上面的例子可以知道第一個引數可以為空,那麼對於作為第一個引數的函式有什麼要求嗎?

>>> map(lambda x:x, (1,2,3),(4,5,6))

Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
    map(lambda x:x, (1,2,3),(4,5,6))
TypeError: <lambda>() takes exactly 1 argument (2 given)

當函式只傳遞一個引數的時候,程式報錯了。根據錯誤資訊:提供了兩個引數,但實際只有一個,所以對第一個引數要求傳入的引數個數必須等於後面系列的個數

>>> map(lambda x,y : x+y, (1,2,3),(4,5,6))
[5, 7, 9]

5. max

max函式有兩種形式:
max(iterable[, key=func]) -> value
  第一種是計算一個可迭代物件的最大值,如果需要對每個元素處理後再計算最大值還可以傳遞一個函式作為比較依據。

  • 計算整數列表中的最大值:
>>> max([1,3,6,2,4,9,8,2,7])
9
>>> max('hello world')
'w'
  • 包含key的情況:計算年齡最大的使用者
>>> users = [{'name':'zhao','age':18},{'name':'qian','age':20},{'name':'sun','age':19}]
>>> max(users, key=lambda item:item['age'])
{'age': 20, 'name': 'qian'}

max(a, b, c, …[, key=func]) -> value
  第二種是直接傳遞多個要比較的元素。

  • 計算多個數字之間的最大值:
>>> max(1,3,6,2,4,9,8,2,7)
9
  • 包含key的情況:計算年齡最大的使用者
>>> max({'name':'zhao','age':18},{'name':'qian','age':20},{'name':'sun','age':19}, key=lambda item:item['age'])
{'age': 20, 'name': 'qian'}

6. min

min函式同max一樣,只不過是用來計算最小值的。

7. set

set方法用來建立一個不重複的集合

>>> set()
set([])
>>> set('hello world')
set([' ', 'e', 'd', 'h', 'l', 'o', 'r', 'w'])
>>> set((1,3,3,4,5,9,7))
set([1, 3, 4, 5, 7, 9])

8. len(object) -> integer

len()函式用來計算一個序列或者集合物件的元素個數

>>> len('hello world')
11
>>> len((1,2,3))
3
>>> len({'name':'zhao','age':18})
2
>>> len(set('hello world'))
8

9. range

range(stop) -> list of integers
生成從0到stop的一個列表,步長為1:

>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

range(start, stop[, step]) -> list of integers
生成列表的時候可以指定步長step,且預設值為1:

>>> range(0,10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(9,-1,-1)
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>>> range(0,10,2)
[0, 2, 4, 6, 8]

10. round(number[, ndigits]) -> floating point number

四捨五入計算,第二個可選引數表示小數點後面的精度。返回的結果跟傳入的資料型別無關,都是float型別。

>>> round(1)
1.0
>>> round(1.2574, 2)
1.26

另外,在math模組中有兩個方法與round方法類似,但是需要先用import math引入才能使用:

  • floor(x)
    取地板計算:返回給定值的整數部分,返回的結果也是float型別。如果引數為整數,則返回結果等同於float(x)
>>> import math
>>> math.floor(1)
1.0
>>> math.floor(1.222)
1.0
>>> math.floor(1.999)
1.0
  • ceil(x)
    取天花板計算:返回比給定值大的最小整數,不過這裡依然是float型別。當給定值為整數型別時,返回結果等同於float(x)
>>> import math
>>> math.ceil(1)
1.0
>>> math.ceil(1.222)
2.0
>>> math.ceil(1.999)
2.0

11. sum(iterable[, start]) -> value

字面意思:求和運算,如果有傳遞start,則最後還要加上start;當序列為空(不是None)時就返回start,start預設為0

>>> sum([])
0
>>> sum([],2)
2
>>> sum([1,2,3,4,5])
15
>>> sum([1,2,3,4,5],6)
21

12. sorted(iterable, cmp=None, key=None, reverse=False) –> new sorted list

對可迭代得物件進行排序,並返回一個新列表
引數說明:
- iterable: 用來排序得可迭代物件
- cmp:預設為None,用來比較iterable中兩個元素得先後順序(類似於Java中的Comparetor)。且這個函式有兩個引數,當大於時返回1,小於時返回-1,等於時返回0
- key:這個引數與max和min函式中的key用法類似,該函式只有一個引數,即迭代物件中的元素
- reverse:False表示升序,True表示降序,預設為升序

下面是對字串中得字母和列表排序:

>>> sorted('hello world')
[' ', 'd', 'e', 'h', 'l', 'l', 'l', 'o', 'o', 'r', 'w']
>>> sorted([8,3,5,7,9,0,1,2,4])
[0, 1, 2, 3, 4, 5, 7, 8, 9]
>>> sorted([8,3,5,7,9,0,1,2,4], reverse=True)
[9, 8, 7, 5, 4, 3, 2, 1, 0]

在其它一些複雜使用場景下,實現cmp函式或者key和reverse組合的方式都可以達到排序的目的

# 測試要用到的資料
>>> persons = [{'name':'zhao','age':18},{'name':'qian','age':20},{'name':'sun','age':19},{'name':'li','age':17}]
  • 實現cmp函式來根據age進行排序:
# 升序
>>> sorted(persons, cmp=lambda x,y:x['age']-y['age'])
[{'age': 17, 'name': 'li'}, {'age': 18, 'name': 'zhao'}, {'age': 19, 'name': 'sun'}, {'age': 20, 'name': 'qian'}]
# 降序
>>> sorted(persons, cmp=lambda x,y:y['age']-x['age'])
[{'age': 20, 'name': 'qian'}, {'age': 19, 'name': 'sun'}, {'age': 18, 'name': 'zhao'}, {'age': 17, 'name': 'li'}]
  • 用key和reverse來實現排序:
# 升序
>>> sorted(persons, key=lambda x:x['age'])
[{'age': 17, 'name': 'li'}, {'age': 18, 'name': 'zhao'}, {'age': 19, 'name': 'sun'}, {'age': 20, 'name': 'qian'}]
# 降序
>>> sorted(persons, key=lambda x:x['age'], reverse=True)
[{'age': 20, 'name': 'qian'}, {'age': 19, 'name': 'sun'}, {'age': 18, 'name': 'zhao'}, {'age': 17, 'name': 'li'}]