內建高階函式

2021-09-29 21:00:46 字數 2221 閱讀 2439

1. map(函式,可迭代物件):使用可迭代物件中的每個元素呼叫函式,將返回值作為新可迭代物件元素;返回值為新可迭代物件。

2. filter(函式,可迭代物件):根據條件篩選可迭代物件中的元素,返回值為新可迭代物件。

3. sorted(可迭代物件,key = 函式,reverse = bool值):排序,返回值為排序結果。

4. max(可迭代物件,key = 函式):根據函式獲取可迭代物件的最大值。

5. min(可迭代物件,key = 函式):根據函式獲取可迭代物件的最小值。

內建高階函式

from common.iterable_tools import iterablehelper

class

wife

:"""

抽象的資料

"""def__init__

(self, name=

"", age=

0, height=

0, weight=0)

: self.name = name

self.age = age

self.height = height

self.weight = weight

def__str__

(self)

:return

"%s--%d--%d--%d"

%(self.name, self.age, self.height, self.weight)

list01 =

[ wife(

"鐵鎚",27

,190

,200),

wife(

"鐵釘",37

,165

,160),

wife(

"鐵棒",24

,160

,190),

wife(

"鐵鍋",23

,190

,100),

]# 需求:在老婆列表中,查詢所有體重大於160的老婆物件

# for item in iterablehelper.find_all(list01,lambda element:element.weight > 160):

# print(item)

# 1. filter 過濾器

for item in

filter

(lambda element: element.weight >

160, list01)

:print

(item)

# 需求:在老婆列表中,查詢所有老婆的姓名與體重

# for item in iterablehelper.select(list01,lambda e:(e.name,e.weight)):

# print(item)

# 2. map 對映

for item in

map(

lambda e:

(e.name, e.weight)

, list01)

:print

(item)

# 需求:在老婆列表中,查詢最重的老婆

# re = iterablehelper.get_max(list01,lambda item:item.weight)

# print(re)

# 3. 獲取最大

re =

max(list01, key=

lambda item: item.weight)

print

(re)

# 4. 排序

# 修改列表內部元素 --> 無需通過返回值傳遞結果

# iterablehelper.order_by(list01,lambda item:item.weight)

# for item in list01:

# print(item)

# 返回排序後的列表

# for item in sorted(list01, key=lambda item: item.weight):

# print(item)

for item in

sorted

(list01, key=

lambda item: item.weight,reverse=

true):

print

(item)

python 內建高階函式

1.map abs i for i in 1,3,4,5 1 對於序列每個元素求絕對值 import random from functools import reduce print list map abs,1,3,4,5 2 對於序列每個元素求階乘 5 import random deffac...

內建函式高階 hash

class foo pass obj1 foo obj2 foo print hash obj1 記憶體位址 136382060082 print hash obj1 記憶體位址 136382060082 print hash obj1 記憶體位址 136382060082 print hash o...

python 內建高階函式

1.map map 函式接收兩個引數,乙個是函式,乙個是序列 map將傳入的函式依次作用到序列的每個元素,並且把結果 作為新的序列返回 求絕對值 print map abs,1,3,4,5 輸出 map列印的不是乙個列表而是乙個物件,所以我們需要轉換為列表才能列印。print list map ab...