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

1.8 递归列出目录里的文件

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

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函数是一种快速定义单行的最小函数,能够用在任何须要函数的地方code

举个例子对象

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

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

匿名函数的优势

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

lambda基础语法

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

lambda语句构建的实际上是一个函数对象io

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.
"""
相关文章
相关标签/搜索