实例讲解python函数式编程
函数式编程是使用一系列函数去解决问题,按照一般编程思维,面对问题时我们的思考方式是“怎么干”,而函数函数式编程的思考方式是我要“干什么”。 至于函数式编程的特点暂不总结,我们直接拿例子来体会什么是函数式编程。
lambda表达式(匿名函数):
普通函数与匿名函数的定义方式:
代码如下:
#普通函数
def add(a,b):
return a + b
print add(2,3)
#匿名函数
add = lambda a,b : a + b
print add(2,3)
#========输出===========
5
匿名函数的命名规则,用lamdba 关键字标识,冒号(:)左侧表示函数接收的参数(a,b) ,冒号(:)右侧表示函数的返回值(a+b)。
因为lamdba在创建时不需要命名,所以,叫匿名函数^_^
Map函数:计算字符串长度
代码如下:
abc = ['com','fnng','cnblogs']
for i in range(len(abc)):
print len(abc[i])
#========输出===========
4
定义abc字符串数组,计算abc长度然后循环输出数组中每个字符串的长度。
来看看map()函数是如何来实现这个过程的。
代码如下:
abc_len = map(len,['hao','fnng','cnblogs'])
print abc_len
#========输出===========
[3, 4, 7]
虽然,输出的结果中是一样的,但它们的形式不同,第一种是单纯的数值了,map()函数的输出仍然保持了数组的格式。
大小写转换;
python提供有了,upper() 和 lower() 来转换大小写。
代码如下:
#大小写转换
ss='hello WORLD!'
print ss.upper() #转换成大写
print ss.lower() #转换成小写
#========输出===========
HELLO WORLD!
hello world!
通过map()函数转换:
代码如下:
def to_lower(item):
return item.lower()
name = map(to_lower,['cOm','FNng','cnBLoGs'])
print name
#========输出===========
['com', 'fnng', 'cnblogs']
这个例子中我们可以看到,我们写义了一个函数toUpper,这个函数没有改变传进来的值,只是把传进来的值做个简单的操作,然后返回。然后,我们把其用在map函数中,就可以很清楚地描述出我们想要干什么。
再来看看普通的方式是如何实现字符串大小写转换的:
代码如下:
abc = ['cOm','FNng','cnBLoGs']
lowname = []
for i in range(len(abc)):
lowname.append(abc[i].lower())
print lowname
#========输出===========
['hao', 'fnng', 'cnblogs']
map()函数加上lambda表达式(匿名函数)可以实现更强大的功能。
代码如下:
#求平方
#0*0,1*1,2*2,3*3,....8*8
squares = map(lambda x : x*x ,range(9))
print squares
#========输出===========
[0, 1, 4, 9, 16, 25, 36, 49, 64]
Reduce函数:
代码如下:
def add(a,b):
return a+b
add = reduce(add,[2,3,4])
print add
#========输出===========
对于Reduce函数每次是需要对两个数据进行处理的,首选取2 和3 ,通过add函数相加之后得到5,接着拿5和4 ,再由add函数处理,最终得到9 。
在前面map函数例子中我们可以看到,map函数是每次只对一个数据进行处理。
然后,我们发现通过Reduce函数加lambda表达式式实现阶乘是如何简单:
代码如下:
#5阶乘
#5!=1*2*3*4*5
print reduce(lambda x,y: x*y, range(1,6))
#========输出===========
Python中的除了map和reduce外,还有一些别的如filter, find, all, any的函数做辅助(其它函数式的语言也有),可以让你的代码更简洁,更易读。 我们再来看一个比较复杂的例子:
代码如下:
#计算数组中正整数的值
number =[2, -5, 9, -7, 2, 5, 4, -1, 0, -3, 8]
count = 0
sum = 0
for i in range(len(number)):
if number[i]>0:
count += 1
sum += number[i]
print sum,count
if count>0:
average = sum/count
print average
#========输出===========
6
如果用函数式编程,这个例子可以写成这样:
代码如下:
number =[2, -5, 9, -7, 2, 5, 4, -1, 0, -3, 8]
sum = filter(lambda x: x>0, number)
average = reduce(lambda x,y: x+y, sum)/len(sum)
print average
#========输出===========
最后我们可以看到,函数式编程有如下好处:
1)代码更简单了。
2)数据集,操作,返回值都放到了一起。
3)你在读代码的时候,没有了循环体,于是就可以少了些临时变量,以及变量倒来倒去逻辑。
4)你的代码变成了在描述你要干什么,而不是怎么去干。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



The speed of mobile XML to PDF depends on the following factors: the complexity of XML structure. Mobile hardware configuration conversion method (library, algorithm) code quality optimization methods (select efficient libraries, optimize algorithms, cache data, and utilize multi-threading). Overall, there is no absolute answer and it needs to be optimized according to the specific situation.

It is impossible to complete XML to PDF conversion directly on your phone with a single application. It is necessary to use cloud services, which can be achieved through two steps: 1. Convert XML to PDF in the cloud, 2. Access or download the converted PDF file on the mobile phone.

There is no built-in sum function in C language, so it needs to be written by yourself. Sum can be achieved by traversing the array and accumulating elements: Loop version: Sum is calculated using for loop and array length. Pointer version: Use pointers to point to array elements, and efficient summing is achieved through self-increment pointers. Dynamically allocate array version: Dynamically allocate arrays and manage memory yourself, ensuring that allocated memory is freed to prevent memory leaks.

There is no APP that can convert all XML files into PDFs because the XML structure is flexible and diverse. The core of XML to PDF is to convert the data structure into a page layout, which requires parsing XML and generating PDF. Common methods include parsing XML using Python libraries such as ElementTree and generating PDFs using ReportLab library. For complex XML, it may be necessary to use XSLT transformation structures. When optimizing performance, consider using multithreaded or multiprocesses and select the appropriate library.

XML formatting tools can type code according to rules to improve readability and understanding. When selecting a tool, pay attention to customization capabilities, handling of special circumstances, performance and ease of use. Commonly used tool types include online tools, IDE plug-ins, and command-line tools.

XML can be converted to images by using an XSLT converter or image library. XSLT Converter: Use an XSLT processor and stylesheet to convert XML to images. Image Library: Use libraries such as PIL or ImageMagick to create images from XML data, such as drawing shapes and text.

An application that converts XML directly to PDF cannot be found because they are two fundamentally different formats. XML is used to store data, while PDF is used to display documents. To complete the transformation, you can use programming languages and libraries such as Python and ReportLab to parse XML data and generate PDF documents.

Use most text editors to open XML files; if you need a more intuitive tree display, you can use an XML editor, such as Oxygen XML Editor or XMLSpy; if you process XML data in a program, you need to use a programming language (such as Python) and XML libraries (such as xml.etree.ElementTree) to parse.
