匿名函数

1. 递归列出目录里的文件

  • os.listdir(),返回指定的文件夹包含的文件或文件夹的名字的列表。这个列表以字母顺序。 它不包括 '.' 和'..' 即使它在文件夹中。
  • os.path.isdir(),判断目录
  • os.path.isfile(),判断文件
  • os.path.join(),连接文件,比如:
In [2]: import os

In [3]: os.path.join('/etc/','passwd','aaa')
Out[3]: '/etc/passwd/aaa'

下面是程序:

#!/usr/bin/python
# -*- coding:utf8 -*-
# author: chawn
# date:
# 此脚本和find 命令类似
import os
import sys
def fun(path):
    # 以列表输出目录下的文件
    lsdir = os.listdir(path)
    # 定义打开的文件和目录,[]重写列表
    dirs = [i for i in lsdir if os.path.isdir(os.path.join(path,i))]
    files = [i for i in lsdir if os.path.isfile(os.path.join(path,i))]
    # 如果是目录,再遍历一次。是文件就输出
    if dirs:# 如果文件的判断条件在目录条件下面,最深层的文件最先列出来。
        for j in dirs:
            fun(os.path.join(path,j))# 现在的目录路径在path下
    if files:
        for k in files:
            print os.path.join(path,k) # 现在的文件路径在path下
# 执行命令时加上参数,并返回对应的值
fun(sys.argv[1])

测试一下/home目录下的所有文件:

[root@t1 py]# python 1.py /home/
/home/g1/.bash_logout
/home/g1/.bash_profile
/home/g1/.bashrc
/home/t1/.bash_logout
/home/t1/.bash_profile
/home/t1/.bashrc
/home/t1/.bash_history
/home/mysql/.bash_logout
/home/mysql/.bash_profile
/home/mysql/.bashrc
/home/mysql/.bash_history
/home/nfstestdir/test.txt
/home/virftp/testuser1/test.txt
/home/virftp/.bash_logout
/home/virftp/.bash_profile
/home/virftp/.bashrc
/home/pure-ftp/.bash_logout
/home/pure-ftp/.bash_profile
/home/pure-ftp/.bashrc
/home/zabbix/.bash_logout
/home/zabbix/.bash_profile
/home/zabbix/.bashrc

2. 匿名函数lambda

  • 定义: lambda函数是一种快速定义单行的最小函数,可以用在任何需要函数的地方
    举例:
In [4]: r =lambda x,y:x*y  #需要括号

In [5]: r(2,3)
Out[5]: 6
  • 匿名函数优点:

1.使用python写一些脚本时,使用lambda可以省去定义函数的过程,让代码更加精简。

  1. 对于一些抽象的,不会被别的地方再重复使用的函数,有时候函数起个名字也是个难题,使用lambda不需要考虑命名的问题。
  2. 使用lambda在某些时候让代码更容易理解。
  • lambda语句中,冒号前是参数,可以有多个,逗号隔开,冒号右边是返回值。
  • lambda语句构建的其实是一个函数对象

举例:
先介绍reduce函数,reduce()传入的函数 f 必须接收两个参数,reduce()对list的每个元素反复调用函数f,并返回最终结果值。

Help on built-in function reduce in module __builtin__:

reduce(...)
    reduce(function, sequence[, initial]) -> value
    
    Apply a function of two arguments cumulatively to the items of a sequence,
    from left to right, so as to reduce the sequence to a single value.
    For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
    ((((1+2)+3)+4)+5).  If initial is present, it is placed before the items
    of the sequence in the calculation, and serves as a default when the
    sequence is empty.

例如,编写一个f函数,接收x和y,返回x和y的和:

def add(x, y):
    return x + y

调用 reduce(add, range(1,101))时,reduce函数将做如下计算:

In [9]: reduce(add,range(1,101))
Out[9]: 5050

有了匿名函数,可以不用事先定义x+y的函数,直接写:

In [10]: reduce(lambda x,y:x+y , range(1,101))
Out[10]: 5050

3. 练习

1.解答

#!/usr/bin/python
# -*- coding:utf8 -*-
# author: chawn
# date:
# 从终端接收若干个数字,要求使用filter()函数,将输入的不是数字的值剔除掉(用户输入的内容有随机性,当我们要接收一个数字的时候,他可能会输入一个字符串过来,要求当用户输入的不是数字,就剔除掉)
def notNum(s):
    for i in s:
       if i.isdigit():
           return True
while True:
    input = raw_input("plz input some nums: ")
    print filter(notNum,list(input))

执行结果:

C:\Users\chawn\PycharmProjects\pyex\venv\Scripts\python.exe C:/Users/chawn/PycharmProjects/pyex/180105/剔除非数字.py
plz input some nums: 45dsafag
['4', '5']
plz input some nums: 455fdaxvdbgaergvweqarg
['4', '5', '5']
plz input some nums: 

2.解答

#!/usr/bin/python
# -*- coding:utf8 -*-
# author: chawn
# date:
#  从终端接收若干个以空格隔开的字符串,然后去除所有的26个字符之外的字符后,打印到屏幕上
# 要求:使用map()函数,map()函数接收两个参数,一个是函数,一个是Iterable,map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回。
def notAlpha(x):
        if x.isalpha():
            print x
while True:
    input = raw_input("plz input sth with blanks: ")
    map(notAlpha,list(input))

执行结果:

C:\Users\chawn\PycharmProjects\pyex\venv\Scripts\python.exe C:/Users/chawn/PycharmProjects/pyex/180105/a.py
plz input sth with blanks: 12222 dsfwaQFQ WEQFR EFQ
d
s
f
w
a
Q
F
Q
W
E
Q
F
R
E
F
Q
plz input sth with blanks: 

由此对比可以看出:map作用的对象是整个list,filter作用对象是list的每个元素。
而且map只是多输出了一个新list,filter改变了原list

3.解答

#!/usr/bin/python
# -*- coding:utf8 -*-
# author: chawn
# date:
#  从终端接收若干个以空格隔开的字符串
# (1).以空格隔开的字符串为用户想要输入的一个值
# (2).用户在输入时不小心按出来了字母键
# 示例如下
# "afda111 dafd222 3dfad33 4ss4dd4"
# 这个字符串,其实是用户想要求 111 222 333 444 的和
# 要求:把每个值中的字母去掉,并计算出所有值的和
# 提示:使用reduce函数,结合前两题使用过的方法,可以很简单的算出
def test(n):
    return filter(lambda x:x.isdigit(),n)

while True:
    n1 = raw_input('Please input somthing:')
    n1=n1.split()
    print reduce(lambda x,y:x+y,map(int,map(test,n1)))

执行结果:

C:\Users\chawn\PycharmProjects\pyex\venv\Scripts\python.exe C:/Users/chawn/PycharmProjects/pyex/180105/啊.py
Please input somthing:1225 fsf5
['1225', '5']
1230
Please input somthing:

你可能感兴趣的:(匿名函数)