官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 大埔县| 奇台县| 阳东县| 武胜县| 宁河县| 常州市| 沂南县| 博白县| 清涧县| 耿马| 沁水县| 东乡县| 诏安县| 海安县| 东乌珠穆沁旗| 红安县| 吴川市| 平原县| 塘沽区| 堆龙德庆县| 兴和县| 贡嘎县| 来宾市| 临泉县| 滦南县| 石屏县| 洛隆县| 灵山县| 葫芦岛市| 庆云县| 佛坪县| 涡阳县| 易门县| 西乌珠穆沁旗| 巴林左旗| 浠水县| 洛南县| 新巴尔虎右旗| 灵丘县| 铁岭市| 蕲春县|