Python high order function use summary!

Yu Liang 2020-11-17 17:05:44
python high order function use


Click on Machine learning algorithm and Python Study , Choose star

Wonderful content doesn't get lost

Datawhale dried food , author : Super money , Xiamen University

This article explains in detail with various practical examples Python5 The use of built-in high-order functions , Can help understand Python And improve the efficiency of data processing , this 5 The functions are :

  • map
  • reduce
  • filter
  • sorted/sort
  • zip

One 、map

1.1 grammar

map The basic syntax of a function is map(func, seq), What it means is : Perform the previous function for each element in the following iteratable sequence func The function of , Finally, we get a new sequence . Be careful :

  • Python2 A list is returned directly from
  • Python3 Is an iterator returned in , If you want to go back to the list , have access to list() To deal with
help(map) # View help information

1.2 demo

By way of example map How to use the function

  1. Use Python Built in functions
  1. Use custom functions
  1. Using anonymous functions lambda

When using anonymous functions, you can have multiple parameters

Two 、reduce

2.1 grammar

reduce Definition of function :

reduce(function, sequence [, initial] ) -> value

reduce Successively sequence One of the elements , And the last call function The result of the parameter , Call again function.

“ First call function when , Provided initial Parameters , Will sequence The first element in and initial Call... As a parameter function, Otherwise, it will be in sequence sequence The first number of ”

2.2 Use

Python3 Has been to reduce Function moves to functools Module , You need to import :

from functools import reduce # Import
help(reduce) # View help documents

The above example is illustrated by a graph :

2.3 demo

  1. Use custom functions
  1. Using anonymous functions lambda

image-20201024185550970

  1. A complex example

The specific process is :

1. 1*2+1=3
2. 3*3+1=10 # first 3 For the above results 3, The first 2 Of the raw data 3
3. 10*4+1=41
  1. Examples with initial values

The initialization value and the first value in the sequence are executed func function , Take the result as the next starting value

# The specific process is interpreted as
1. 6+1=7
2. 7+2=9
3. 9+3=12
4. 12+4=16
5. 16+5=21

3、 ... and 、filter

3.1 grammar

filter() Function to filter the sequence , Filter out the elements that don't meet the criteria , Returns the eligible elements to form a new list .

Each element in the sequence is passed as an argument to the function for judgment , return True perhaps False, And then it will return True Is placed in the new list .

filter() The grammar is as follows :

filter(function, iterable) # The former is a function , The latter is the sequence to be executed

3.2 demo

help(filter) # Help document
  1. Use custom functions

return 10 An even number within

  1. Using anonymous functions lambda
  1. Filtering of strings

Select a string that meets the specified requirements

Four 、sorted

4.1 grammar

sorted(iterable, key=None, reverse=False)

4.2 3 Parameters

sorted() Accept 3 Parameters , It returns a sorted list

  • Iteratable object iterable
  • reverse=False, Accept a Boolean value , Choose whether to reverse the sort results , The default is False
  • Accept a callback function key=None, The callback function can only have one parameter , Sort according to the return value of the function

4.3 demo

help(sorted) # Help document
  1. The default is not reversed
  1. Pair tuple 、range object 、 The order of dictionaries

4.4 Result reversal

The meaning of the result reversal is Arrange the results in descending order , Because the original default is ascending , It uses reverse=True

4.5 understand key

key The function of the parameter is to define a function , Then, by applying the elements in the sequence to the function, we sort it

Here we use Absolute value function

4.6 contrast sort()

sort() The method can only be To the original list list Sort , Parameters and sorted It's the same

The result is to modify the original list directly in place , and sorted It's generating a new list , The two are different

5、 ... and 、zip

zip() yes Python One of the most important methods in , It can realize many functions quickly .

5.1 grammar

zip([iterable,...]) # iterable It's one or more iterators
  • The result of function execution is in Python3 It's a zip object , If you need to show it in the form of a list , Use it directly list Method expansion ; The result of the expansion is in the form of nested tuples in the list
  • stay Python2 What is directly returned in is Tuple list form
help(zip) # To view the document

5.2 zip Take a sequence

zip It is acceptable that list 、 Tuples 、 character string The form such as

zip Accept the form of an empty list , The returned list is still empty

5.3 zip Accept multiple sequences

At the same time Combine different types of sequences

5.4 The processing length is different

When multiple sequences exist at the same time , Take the length of the sequence with the smallest length

5.5 zip(*iterables)

We generally think that this method is zip The reverse process of , It's a unzip The process of , Give an example of its use :

5.6 Complex examples

Let's take a more complex example

The explanation for this example is :

  1. [x] It's a list with a list ,x It's a list in itself
  2. [x]*3 The result is [x,x,x], In fact [[4,5,6],[4,5,6],[4,5,6]]
  3. [*[x]*3] The result is [(4,4,4),(5,5,5),(6,6,6)]

5.7 zip Application

Pass below zip To illustrate its application :

  1. Sum list
  1. Data merging
  1. Dictionary key-value transformation

for Cycle to achieve :

Use zip Realization :

Click... If you like “ Looking at ” Well !

This article is from WeChat official account. - Machine learning algorithm and Python Study (MLPython)

The source and reprint of the original text are detailed in the text , If there is any infringement , Please contact the yunjia_community@tencent.com Delete .

Original publication time : 2020-11-10

Participation of this paper Tencent cloud media sharing plan , You are welcome to join us , share .

版权声明
本文为[Yu Liang]所创,转载请带上原文链接,感谢

  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database