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