- Python Data Structures and Algorithms
- Benjamin Baka
- 393字
- 2021-07-09 19:44:59
Higher order functions
Functions that take other functions as arguments, or that return functions, are called higher order functions. Python 3 contains two built-in higher order functions, filter() and map(). Note that in earlier versions of Python, these functions returned lists; in Python 3, they return an iterator, making them much more efficient. The map() function provides an easy way to transform each item into an iterable object. For example, here is an efficient, compact way to perform an operation on a sequence. Note the use of the lambda anonymous function:

Similarly, we can use the filter built-in function to filter items in a list:

Note that both map and filter perform the identical function as to what can be achieved by list comprehensions. There does not seem to be a great deal of difference in the performance characteristics apart from a slight performance advantage when using the in built functions map and filter without the lambda operator, compared to list comprehensions. Despite this, most style guides recommend the use of list comprehensions over built-in functions, possibly because they tend to be easier to read.
Creating our own higher order functions is one of the hallmarks of functional programming style. A practical example of how higher order functions can be useful is demonstrated by the following. Here we are passing the len function as the key to the sort function. This way, we can sort a list of words by length:

Here is another example for case-insensitive sorting:

Note the difference between the list.sort() method and the sorted built-in function. list.sort(), a method of the list object, sorts the existing instance of a list without copying it. This method changes the target object and returns None. It is an important convention in Python that functions or methods that change the object return None to make it clear that no new object was created and that the object itself was changed.
On the other hand, the sorted built-in function returns a new list. It actually accepts any iterable object as an argument, but it will always return a list. Both list sort and sorted take two optional keyword arguments as key.
A simple way to sort more complex structures is to use the index of the element to sort using the lambda operator, for example:

Here we have sorted the items by price.
- 黑客攻防從入門到精通(實戰(zhàn)秘笈版)
- scikit-learn Cookbook
- 一步一步學(xué)Spring Boot 2:微服務(wù)項目實戰(zhàn)
- DevOps with Kubernetes
- Python for Secret Agents:Volume II
- Visual C++實例精通
- 青少年美育趣味課堂:XMind思維導(dǎo)圖制作
- 從程序員到架構(gòu)師:大數(shù)據(jù)量、緩存、高并發(fā)、微服務(wù)、多團(tuán)隊協(xié)同等核心場景實戰(zhàn)
- Bootstrap Essentials
- Getting Started with LLVM Core Libraries
- 從零開始學(xué)C語言
- Azure Serverless Computing Cookbook
- Learning Node.js for .NET Developers
- 零基礎(chǔ)學(xué)Python編程(少兒趣味版)
- 寫給大家看的Midjourney設(shè)計書