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

本文深入探讨了Python中递归函数的应用,通过实例讲解如何使用递归来遍历目录及其子目录下的所有文件。此外,文章还介绍了Lambda匿名函数的概念、语法及优势,展示了其在代码简化和特定场景下的高效应用。

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

转载于:https://my.oschina.net/u/4030294/blog/2963645

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值