首页 > 编程语言 >Python - Functional programming

Python - Functional programming

时间:2024-07-31 17:31:21浏览次数:17  
标签:function map functions Python programming Functional argument returns iterable

Functional programming is a programming paradigm in which most of the work in a program is done using pure functions. A pure function is a function without any side effects; its return value is always determined by its input arguments, so it always returns the same output, given the same input. In Python, functional programming is supported by the higher-order functions map, filter, and reduce.

map(func, iterable)

filter(func, iterable)

reduce(func, iterable)

map and filter are built-in functions while reduce is present in functools module. These functions can replace for loops and if statements and hence can make the code shorter. So, using these functions makes the code concise as the control flow statements can be replaced by expressions, and the programmer can focus on solving the actual problem instead of going into the details of looping and branching.

These functions are not used much because now Python has better alternatives in the form of comprehensions and generators which we have already seen before. If you are writing your code and you can do the same thing with a comprehension, then it is better to use a comprehension since they are considered more Pythonic and are preferred by the Python community. Although these functions are not used very often, you might encounter them in some code that you are using so it is good to be familiar with them. All these functions have a parameter that accepts a function as an argument. Generally, the functions that are to be sent as arguments to these functions are single-expression throw-away functions. So, we mostly use lambda expressions as arguments to these functions instead of defining separate def statements

 

map

map(func, iterable)

The map function takes in a function and an iterable as argument. The function that is sent, should be such that it takes in a single argument and returns a single value. The second argument can be any iterable like list or a tuple; the values inside the iterable should be acceptable as arguments to the first function.

This map function returns a map object which is an iterator in which each item is obtained by applying the argument function to each element of the iterable. An iterator is returned instead of a list for efficiency reasons.

 

map with multiple iterables

map(func, iterable1, iterable2, ………… )

It is possible to send more than one iterable in the map function, but the condition is that the number of arguments in the function func should be equal to the number of iterables that are sent to the map function. For example, if we send three iterables, then the function func should be such that it takes 3 arguments and returns a single value. The arguments to the function are received from the corresponding iterables. Here is an example-

>>> def multiply(x, y, z):

...  return x * y * z

...

>>> map(multiply, [1,2,3,4], (4,5,6,7), [10,20,30,40])

<map object at 0x000002A61232AE30>

 

filter

The built-in function filter is used to filter out elements of an iterable depending on the result of another function.

filter(func, iterable)

This function takes two arguments, a function and an iterable. The argument function func should be such that it accepts a single argument and returns a Boolean value, which means that it should return either True or False. The second argument can be any iterable like list, set or tuple.

The filter function returns a filter object which is an iterator that produces only those items of iterable for which the function func returns True. The argument function is applied to each element of the iterable; if the function returns True for an element then that element will be produced by the iterator. So, we can say that it filters out all the elements for which the function returns False. Let us understand this with the help of an example.

 

Reducing an iterable

The function reduce reduces an iterable to a single value, which means that it returns a single value for the whole iterable.

reduce(func, iterable)

This function takes two arguments, first is a function and second is an iterable. The argument function should be such that it takes two arguments and returns a single value. The function reduce works by continually calling the argument function for the successive elements of the iterable, computing and accumulating the results, till the iterable is reduced to a single value.

The argument function is invoked with the first and second values of the iterable, followed by computation of the result. Subsequently, the function is invoked with this result and the third value, with the process repeating for the fourth value and beyond. This continues till all the values in the iterable are used.

 

标签:function,map,functions,Python,programming,Functional,argument,returns,iterable
From: https://www.cnblogs.com/zhangzhihui/p/18335070

相关文章

  • Python - Lambda expressions as closures
    Aclosureisanestedfunctionthatcanaccessfreevariablesfromanenclosingfunctionevenafterithasfinisheditsexecution.Weknowthat,likenestedfunctiondefinitions,lambdaexpressionscanreferencevaluesfromtheenclosingscope,solambda......
  • Python - Creating jump tables using lambda functions
    Wecanplacelambdafunctioninsidelistanddictionaryliterals.Thiswaywecanuselambdaexpressionstocreatejumptables.>>>L=[lambdas:s.strip().lower(),... lambdas:s.strip().upper(),... lambdas:s.lstrip().title(),... lambd......
  • exceptionx:灵活便捷的Python异常处理库,让异常处理更高效!
    exceptionxEnglish|中文exceptionx是一个灵活且便捷的Python异常处理库,允许你动态创建异常类,并提供多种异常处理机制。exceptionx的前身是gqylpy-exception。pip3installexceptionx动态创建异常使用exceptionx,你可以在需要时即时创建异常类,而无需提前定义。例如,如......
  • systempath:Python开发者必备的文件与系统路径操作神器!
    systempath-专业级的文件与系统路径操作库English|中文systempath是一个专为Python开发者设计的,高度专业化的文件与系统路径操作库。通过提供一套直观且功能强大的面向对象API,它极大地简化了复杂文件与目录管理的任务,使开发者能够更专注于核心业务逻辑的实现,而非底层文件系......
  • 用Python打造精彩动画与视频,3.3 添加音频和简单效果
     3.3添加音频和简单效果在本节中,我们将学习如何使用MoviePy库为视频添加音频和一些简单的效果。这些操作可以让你的视频更具吸引力和个性化。准备工作首先,确保你已经安装了MoviePy和pydub库。你可以通过以下命令安装:pipinstallmoviepypydub同时,你需要确保系统......
  • 用Python打造精彩动画与视频,3.2 基本的剪辑和合并操作
     3.2基本的剪辑和合并操作在这一节中,我们将学习如何使用MoviePy库对视频进行基本的剪辑和合并操作。MoviePy是一个用于视频编辑的Python库,可以轻松地实现视频的剪辑、合并、添加音频等操作。准备工作首先,确保你已经安装了MoviePy库。你可以通过以下命令安装:pipins......
  • 计算机毕业设计django/flask导师双选指导系统python+vue
    通过分析企业对于本科生导师指导平台的需求,创建了一个计算机管理本科生导师指导平台的方案。文章介绍了本科生导师指导平台的系统分析部分,包括可行性分析等,系统设计部分主要介绍了系统功能设计和数据库设计。 Python版本:python3.7+前端:vue.js+elementui框架:django/flask都......
  • 农产品商城自主供销服务系统 微信小程序-python+uniapp
    小程序端运行软件 微信开发者工具/hbuiderxuni-app框架:使用Vue.js开发跨平台应用的前端框架,编写一套代码,可编译到Android、小程序等平台。农产品供销系统是基于微信小程序开发,本系统分为用户,管理员,商家三个角色;用户功能是注册登陆后,在线购买商品,加入购物车,生成订单,在线咨......
  • VSCode:Python 虚拟环境未在集成终端中自动激活
    我最近安装了VSCode,并注意到当我打开集成终端时,Python虚拟环境不会自动激活。从此链接中VSCode内提供的信息:https://github.com/microsoft/vscode-python/wiki/Activate-Environments-in-Terminal-Using-Environment-Variables看来Python扩展可能不会对......
  • Python 中的多元回归
    我想在Python中基于多个相关数据数组和多个独立数据执行多元线性回归。我见过很多多重线性回归,具有多个独立输入,几乎每个人都认为多重=多元,但事实并非如此。我在互联网上看不到任何真正的多元教程。我想要的是多个输出+多个输入。frompandasimportDataFramefromsklear......