Home Backend Development Python Tutorial Python中的特殊语法:filter、map、reduce、lambda介绍

Python中的特殊语法:filter、map、reduce、lambda介绍

Jun 10, 2016 pm 03:15 PM
filter lambda map python reduce

filter(function, sequence):对sequence中的item依次执行function(item),将执行结果为True的item组成一个List/String/Tuple(取决于sequence的类型)返回:

复制代码 代码如下:

>>> def f(x): return x % 2 != 0 and x % 3 != 0
>>> filter(f, range(2, 25))
[5, 7, 11, 13, 17, 19, 23]
>>> def f(x): return x != 'a'
>>> filter(f, "abcdef")
'bcdef'

map(function, sequence) :对sequence中的item依次执行function(item),见执行结果组成一个List返回:

复制代码 代码如下:

>>> def cube(x): return x*x*x
>>> map(cube, range(1, 11))
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
>>> def cube(x) : return x + x
...
>>> map(cube , "abcde")
['aa', 'bb', 'cc', 'dd', 'ee']

另外map也支持多个sequence,这就要求function也支持相应数量的参数输入:
复制代码 代码如下:

>>> def add(x, y): return x+y
>>> map(add, range(8), range(8))
[0, 2, 4, 6, 8, 10, 12, 14]

reduce(function, sequence, starting_value):对sequence中的item顺序迭代调用function,如果有starting_value,还可以作为初始值调用,例如可以用来对List求和:

复制代码 代码如下:

>>> def add(x,y): return x + y
>>> reduce(add, range(1, 11))
55 (注:1+2+3+4+5+6+7+8+9+10)
>>> reduce(add, range(1, 11), 20)
75 (注:1+2+3+4+5+6+7+8+9+10+20)

lambda:这是Python支持一种有趣的语法,它允许你快速定义单行的最小函数,类似与C语言中的宏,这些叫做lambda的函数,是从LISP借用来的,可以用在任何需要函数的地方:

复制代码 代码如下:

>>> g = lambda x: x * 2
>>> g(3)
6
>>> (lambda x: x * 2)(3)
6

我们也可以把filter map reduce 和lambda结合起来用,函数就可以简单的写成一行。
例如:

复制代码 代码如下:

kmpathes = filter(lambda kmpath: kmpath,                 
map(lambda kmpath: string.strip(kmpath),
string.split(l, ':')))    

看起来麻烦,其实就像用语言来描述问题一样,非常优雅。
对 l 中的所有元素以':'做分割,得出一个列表。对这个列表的每一个元素做字符串strip,形成一个列表。对这个列表的每一个元素做直接返回操作(这个地方可以加上过滤条件限制),最终获得一个字符串被':'分割的列表,列表中的每一个字符串都做了strip,并可以对特殊字符串过滤。

---------------------------------------------------------------

lambda表达式返回一个函数对象
例子:

复制代码 代码如下:

func = lambda x,y:x+y
func相当于下面这个函数
def func(x,y):
    return x+y

注意def是语句而lambda是表达式
下面这种情况下就只能用lambda而不能用def
复制代码 代码如下:

[(lambda x:x*x)(x) for x in range(1,11)]

map,reduce,filter中的function都可以用lambda表达式来生成!
 
map(function,sequence)
把sequence中的值当参数逐个传给function,返回一个包含函数执行结果的list。
如果function有两个参数,即map(function,sequence1,sequence2)。
 
例子:
求1*1,2*2,3*3,4*4

复制代码 代码如下:

map(lambda x:x*x,range(1,5))

返回值是[1,4,9,16]
 
reduce(function,sequence)

function接收的参数个数只能为2
先把sequence中第一个值和第二个值当参数传给function,再把function的返回值和第三个值当参数传给
function,然后只返回一个结果。
 
例子:
求1到10的累加

复制代码 代码如下:

reduce(lambda x,y:x+y,range(1,11))

返回值是55。
 
filter(function,sequence)

function的返回值只能是True或False
把sequence中的值逐个当参数传给function,如果function(x)的返回值是True,就把x加到filter的返回值里面。一般来说filter的返回值是list,特殊情况如sequence是string或tuple,则返回值按照sequence的类型。
 
例子:
找出1到10之间的奇数

复制代码 代码如下:

filter(lambda x:x%2!=0,range(1,11))

返回值
复制代码 代码如下:

[1,3,5,7,9]

 
如果sequence是一个string
复制代码 代码如下:

filter(lambda x:len(x)!=0,'hello')返回'hello'
filter(lambda x:len(x)==0,'hello')返回''

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1663
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

See all articles