1.8 递归列出目录里的文件 1.9 匿名函数

1.8 递归列出目录里的文件

这个需求类似于find,把目录以及其子目录的文件和目录列出来

os模块的几个方法

os.listdir('dir')  \\列出路径下的所有文件及目录
os.path.isdir(‘dir’) \\判断是否是目录
os.path.isfile(‘file’)  \\判断时候是文件
os.path.join('dir1','dir2')  \\将几个路径连接起来,输出dir1/dir2

脚本写法

import os
import sys
def print_files(path):
	lsdir = os.listdir(path)
	dirs = [os.path.join(path,i) for i in lsdir if os.path.isdir(os.path.join(path,i))]  \\列表重写
	files = [os.path.join(path,i) for i in lsdir if os.path.isfile(os.path.join(path,i))]
	if files :
		for i in files:
			print i
	if dirs :
		for d in dirs:
			print_files(d)  \\if files 和 if dirs交换位置,则会先打印深层文件 
print_files(sys.argv[1])

这个函数本身就是收敛的,不需要做收敛判断

1.9 匿名函数lambda

lambda函数是一种快速定义单行的最小函数,可以用在任何需要函数的地方

举个例子

def fun(x,y):
	return x*y
fun(2,3)

r = lambda x,y:x*y
r(2,3)

匿名函数的优点

1、使用python歇写一些脚本时,使用lambda可以省去定义函数的过程,使代码更加精简 2、对于一些抽象的。不会被别的地方重复使用的函数,可以省去给函数起名的步骤,不用考虑重名的问题 3、使用lambda在某些时候让代码更容易理解

lambda基础语法

lambda语句中,冒号前的参数,可以有多个,逗号分隔开,冒号右边是返回值

lambda语句构建的其实是一个函数对象

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

"""
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.
"""

猜你喜欢

转载自my.oschina.net/u/4030294/blog/2963645
1.9