搜尋
首頁後端開發Python教學Python中lambda表達式的簡單介紹(附範例)

本篇文章帶給大家的內容是關於Python中lambda表達式的簡單介紹(附範例),有一定的參考價值,有需要的朋友可以參考一下,希望對你有幫助。

一:匿名函數的定義

lambda parameter_list: expression

二:三元表達式

條件為真時傳回的結果if 條件判斷else 條件為假的時候回傳的結果

三:map

map(func(arg1, arg2...), list1_arg1, list2_arg2),對後面輸入的list分別執行前面的函數(數學的映射)

四:reduce

reduce(func(arg1, arg2...), list1_arg, init_value),連續計算,連續呼叫lambda表達式

五:filter

filter(func(arg1, arg2...), list1_arg1)當條件滿足的時候資料會被過濾出來!

六:函數式程式設計與命令式程式設計

def
    if --else
    for
    map reduce filter
    lambda

函數式程式設計的想法。 。 。 。
命令式程式設計的想法。 。 。 。

函數式程式設計關心資料的映射,命令式程式設計關心解決問題的步驟

函數式程式設計:

(1)指的是函數與其他資料型別一樣,處於平等地位,可以賦值給其他變量,也可以當作參數,傳入另一個函數,或是作為別的函數的回傳值。

(2) 只用"表達式",不用"語句"

from functools import reduce
# ----------------------------------------------------------------#
#   匿名函数的定义
# ----------------------------------------------------------------#


def add(x, y):
    """
    add x and y
    :param x: x can be str or num
    :param y: y can be str or num
    :return:  x+y
    """
    return x + y


# lambda parameter_list: expression
user_sum = lambda arg1, arg2: arg1 + arg2

my_sum = user_sum(2, 2)
print(my_sum)

# ----------------------------------------------------------------#
#   三元表达式
# ----------------------------------------------------------------#
a, b = 1, 2
r = a if a > b else b
print(r)

# ----------------------------------------------------------------#
#   map(func, list),对后面输入的list分别执行前面的函数(数学的映射)
# ----------------------------------------------------------------#

myListMap1 = [1, 2, 3, 4]
myNewListMap1 = map(lambda x: x ** 2, myListMap1)  # 返回为map类型的数据结构
print(type(myNewListMap1))
print('myNewListMap1:', list(myNewListMap1))    # 转换为list


# 两个或者多个参数的map函数的使用
# 当两个参数种元素的个数不相同的时候会截断
myListMap2 = [1, 2, 3, 4]
myNewListMap2 = map(lambda x, y: x + y, myListMap1, myListMap2)
print('myNewListMap2:', list(myNewListMap2))


# ----------------------------------------------------------------#
#   reduce(func, list)连续计算,连续调用lambda表达式
# ----------------------------------------------------------------#

myListReduce = [1, 2, 3, 4]
# 把list中的值一个一个放进lambda中
r = reduce(lambda x, y: x + y, myListReduce)
print(r)

# 对第一个函数参数进行初始化
r = reduce(lambda x, y: x + y, myListReduce, 10)
print(r)

# filter
myListFilter = [3, 5, 6, 7, 8, 9, 10]
myNewListFilter = filter(lambda x: x % 2 == 1, myListFilter)
print('myNewListFilter:', list(myNewListFilter))

list_x = [1, 1, 0, 0]
filter_list = filter(lambda x: True if x == 1 else False, list_x)
print(list(filter_list))

以上是Python中lambda表達式的簡單介紹(附範例)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:博客园。如有侵權,請聯絡admin@php.cn刪除
可以在Python數組中存儲哪些數據類型?可以在Python數組中存儲哪些數據類型?Apr 27, 2025 am 12:11 AM

pythonlistscanStoryDatatepe,ArrayModulearRaysStoreOneType,and numpyArraySareSareAraysareSareAraysareSareComputations.1)列出sareversArversAtileButlessMemory-Felide.2)arraymoduleareareMogeMogeNareSaremogeNormogeNoreSoustAta.3)

如果您嘗試將錯誤的數據類型的值存儲在Python數組中,該怎麼辦?如果您嘗試將錯誤的數據類型的值存儲在Python數組中,該怎麼辦?Apr 27, 2025 am 12:10 AM

WhenyouattempttostoreavalueofthewrongdatatypeinaPythonarray,you'llencounteraTypeError.Thisisduetothearraymodule'sstricttypeenforcement,whichrequiresallelementstobeofthesametypeasspecifiedbythetypecode.Forperformancereasons,arraysaremoreefficientthanl

Python標準庫的哪一部分是:列表或數組?Python標準庫的哪一部分是:列表或數組?Apr 27, 2025 am 12:03 AM

pythonlistsarepartofthestAndArdLibrary,herilearRaysarenot.listsarebuilt-In,多功能,和Rused ForStoringCollections,而EasaraySaraySaraySaraysaraySaraySaraysaraySaraysarrayModuleandleandleandlesscommonlyusedDduetolimitedFunctionalityFunctionalityFunctionality。

您應該檢查腳本是否使用錯誤的Python版本執行?您應該檢查腳本是否使用錯誤的Python版本執行?Apr 27, 2025 am 12:01 AM

ThescriptisrunningwiththewrongPythonversionduetoincorrectdefaultinterpretersettings.Tofixthis:1)CheckthedefaultPythonversionusingpython--versionorpython3--version.2)Usevirtualenvironmentsbycreatingonewithpython3.9-mvenvmyenv,activatingit,andverifying

在Python陣列上可以執行哪些常見操作?在Python陣列上可以執行哪些常見操作?Apr 26, 2025 am 12:22 AM

Pythonarrayssupportvariousoperations:1)Slicingextractssubsets,2)Appending/Extendingaddselements,3)Insertingplaceselementsatspecificpositions,4)Removingdeleteselements,5)Sorting/Reversingchangesorder,and6)Listcomprehensionscreatenewlistsbasedonexistin

在哪些類型的應用程序中,Numpy數組常用?在哪些類型的應用程序中,Numpy數組常用?Apr 26, 2025 am 12:13 AM

NumPyarraysareessentialforapplicationsrequiringefficientnumericalcomputationsanddatamanipulation.Theyarecrucialindatascience,machinelearning,physics,engineering,andfinanceduetotheirabilitytohandlelarge-scaledataefficiently.Forexample,infinancialanaly

您什麼時候選擇在Python中的列表上使用數組?您什麼時候選擇在Python中的列表上使用數組?Apr 26, 2025 am 12:12 AM

useanArray.ArarayoveralistinpythonwhendeAlingwithHomoGeneData,performance-Caliticalcode,orinterfacingwithccode.1)同質性data:arraysSaveMemorywithTypedElements.2)績效code-performance-calitialcode-calliginal-clitical-clitical-calligation-Critical-Code:Arraysofferferbetterperbetterperperformanceformanceformancefornallancefornalumericalical.3)

所有列表操作是否由數組支持,反之亦然?為什麼或為什麼不呢?所有列表操作是否由數組支持,反之亦然?為什麼或為什麼不呢?Apr 26, 2025 am 12:05 AM

不,notalllistoperationsareSupportedByArrays,andviceversa.1)arraysdonotsupportdynamicoperationslikeappendorinsertwithoutresizing,wheremactsperformance.2)listssdonotguaranteeconecontanttanttanttanttanttanttanttanttanttimecomplecomecomplecomecomecomecomecomecomplecomectacccesslectaccesslecrectaccesslerikearraysodo。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!