1. 程式人生 > 其它 >python 中常用的高階函式

python 中常用的高階函式

filter 過濾

  • filter() 函式用於過濾序列,過濾掉不符合條件的元素,返回由符合條件元素組成的新列表。
  • 語法:filter(function, iterable)
  • 引數:function(判斷函式),iterable (可迭代物件)
  • 返回值:
    • Python 2.x 返回列表
    • Python 3.x 返回迭代器
# python 2.7
def is_odd(n):
    return n % 2 == 1
alist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(alist)
# python 3.x
def
is_odd(n): return n % 2 == 1 alist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) newlist = list(alist) print(newlist)

map 對映

  • 接收一個函式 f 和一個或多個序列 list,並通過把函式 f 依次作用在 序列 list 的每個元素上,得到一個新的 list 並返回。
  • 語法:map(function, iterable, …)
  • 引數:function – 函式,iterable – 一個或多個序列
  • 返回值:
    • Python 2.x 返回列表
    • Python 3.x 返回迭代器
# 計算平方數
def square(x) :
    return x ** 2
map_result = map(square, [1,2,3,4,5])
# 計算列表各個元素的平方值
print(list(map_result))

sorted 排序

  • 對所有可迭代的物件進行排序操作。
  • 語法:sorted(mylist, [reverse,key])
  • 引數:
    • mylist,需要被排序的可迭代物件
    • reverse 排序規則(reverse = True 降序 , reverse = False 升序(預設))
    • key:指定的函式將作用於 list 的每一個元素上,並根據 key 函式返回的結果進行排序
  • 返回值:返回重新排序的列表
>>> before=[1,4,2,5,0]
>>> after=sorted(before)
>>> after
[0, 1, 2, 4, 5]
>>> before
[1, 4, 2, 5, 0]
## 倒序排序
>>> after1=sorted(before,reverse=True)
>>> after1
[5, 4, 2, 1, 0]
## 使用規則排序,key為abs,對前面的一組資料取絕對值 ,然後再排序
>>> sorted([-1,4,3,2,0],key=abs)
[0, -1, 2, 3, 4]

總結

python 中提供了一些內建的高階函式,可以很方便的處理資料序列。
比如:對列表中的所有資料進行運算得到一組新的資料,對序列中的資料進行排序等等。不需要導包,可以直接拿過來使用,常用的 filter,map,sorted 等等。: