Python之map、filter、sorted

一、Map函數

map函數是python內置的函數(工廠函數),使用help(map)查看map函數的說明信息。

>>> help(map)
class map(object)
 |  map(func, *iterables) --> map object
 |  
 |  Make an iterator that computes the function using arguments from
 |  each of the iterables.  Stops when the shortest iterable is exhausted.
 |  
 |  Methods defined here:
	……

map功能描述:生成一個迭代器,該迭代器使用來自每個iterable的參數計算函數。當最短的iterable耗盡時停止。

map函數必須傳入兩個參數:

  • func:函數。
  • iterables:可迭代對象(可以被for循環遍歷的對象),list、tuple、dict、生成器、迭代器等。

map返回的對象是Iterator,是惰性序列,實際計算行爲在調用next函數處理的時候才進行。

map函數將返回一個迭代器(iterator)對象。

>>> from collections import Iterator
>>>a = map(lambda x:x, range(3))
>>> isinstance(a, Iterator)
True

當對返回的迭代器使用next方法時會將傳進來的可迭代對象的一個對象放到函數中進行處理,並返回結果,當遍歷完最後一個對象,再使用next方法時會拋出StopIteration異常。

>>> next(a)
0
>>> next(a)
1
>>> next(a)
2
>>> next(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

二、Filter函數

運行help(filter)查看filter函數的說明信息。

class filter(object)
 |  filter(function or None, iterable) --> filter object
 |  
 |  Return an iterator yielding those items of iterable for which function(item)
 |  is true. If function is None, return the items that are true.

filter功能描述:從iterable中獲取對象(item)放進函數中進行處理,只保留函數返回的結果可判斷爲True的項(item)。如果第一個參數爲None,則返回iterable中判斷爲True的對象。

function函數要求傳入兩個參數:

  • function or None:函數或者None;
  • iterable:可迭代對象(可以被for循環遍歷的對象),list、tuple、dict、生成器、迭代器等。

filter返回的對象是Iterator,是惰性序列,實際過濾行爲在調用next函數處理的時候才進行。

filter函數將返回一個迭代器(iterator)對象。

以下函數將過濾偶數並返回一個迭代器。

>>> a = filter(lambda x: x % 2 == 0, range(4))
>>> type(a)
<class 'filter'>
>>> isinstance(a, Iterator)
True
>>> print(list(a))
[0, 2]

三、Sorted函數

運行help(sorted)查看filter函數的說明信息。

sorted(iterable, /, *, key=None, reverse=False)
    Return a new list containing all items from the iterable in ascending order.
    
    A custom key function can be supplied to customize the sort order, and the
    reverse flag can be set to request the result in descending order.

sorted函數功能描述:以列表的形式,將iterable中的對象按升序進行排序後的結果返回。sorted函數允許自定義函數來處理iterable中的每個結果,按函數返回的結果進行排序。

sorted函數至少傳進一個參數:

  • iterable:可迭代對象(可以被for循環遍歷的對象),list、tuple、dict、生成器、迭代器等。
  • key:可選參數,默認爲None,可以指向一個函數。
  • reverse:默認爲False,如果設置爲True,將逆轉排序後的結果。

使用filter函數對列表進行排序:

>>> a = [2,1,7,3,6,9,4]
>>> b = sorted(a)
>>> print(b)
[1, 2, 3, 4, 6, 7, 9]

需要進行降序排序,只需將reverse設置爲True:

>>> a = [2,1,7,3,6,9,4]
>>> b = sorted(a, reverse=True)
>>> print(b)
[9, 7, 6, 4, 3, 2, 1]

自定義函數將奇、偶數分開:

>>> a = [2,1,7,3,6,9,4]
>>> def func1(x):
...     return x % 2 == 0
>>> b = sorted(a, key=func1)
>>> print(b)
[1, 7, 3, 9, 2, 6, 4]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章