- Mastering Python Scripting for System Administrators
- Ganesh Sanjiv Naik
- 186字
- 2021-07-02 14:00:29
Lambda functions
In Python, an anonymous function is a function that is defined without a name and is called a lambda function, as it is defined using a keyword lambda. We use these functions whenever we require a function for a short period of time.
Lambda functions are used along with built-in functions, such as filter(), and map().
The filter() function returns a list of elements and has only one iterable as input. The following shows an example using filter():
numbers = [10, 25, 54, 86, 89, 11, 33, 22]
new_numbers = list(filter(lambda x: (x%2 == 0) , numbers))
print(new_numbers)
Output:
[10, 54, 86, 22]
In this example, the filter() function is taking a lambda function and a list as an argument.
The map() function returns a list of results after applying the specified function. Now, let's look at an example using map():
my_list = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = list(map(lambda x: x * 2 , my_list))
print(new_list)
Output:
[2, 10, 8, 12, 16, 22, 6, 24]
Here, the map() function is taking a lambda function and a list.
推薦閱讀
- ASP.NET Core:Cloud-ready,Enterprise Web Application Development
- JavaScript 從入門到項(xiàng)目實(shí)踐(超值版)
- Mastering RabbitMQ
- Arduino開發(fā)實(shí)戰(zhàn)指南:LabVIEW卷
- NLTK基礎(chǔ)教程:用NLTK和Python庫(kù)構(gòu)建機(jī)器學(xué)習(xí)應(yīng)用
- 趣學(xué)Python算法100例
- 深入理解Java7:核心技術(shù)與最佳實(shí)踐
- Learning Apache Kafka(Second Edition)
- PhoneGap Mobile Application Development Cookbook
- Visual Basic程序設(shè)計(jì)實(shí)驗(yàn)指導(dǎo)(第二版)
- Mastering Xamarin.Forms(Second Edition)
- Go語(yǔ)言精進(jìn)之路:從新手到高手的編程思想、方法和技巧(2)
- Geospatial Development By Example with Python
- Python機(jī)器學(xué)習(xí)算法與應(yīng)用
- Hadoop 2.X HDFS源碼剖析