Python lambda匿名函數,遞歸應用
‘‘‘
Lambda函數能接收任何數量的參數但只能返回一個表達式的值
匿名函數不能直接調用print,因為lambda需要一個表達式
‘‘‘
sum = lambda x, y: x + y
print(‘x+y=‘, sum(2, 6))
‘‘‘
匿名函數應用
‘‘‘
def test_nm(a, b, func):
result = func(a, b)
return result
print(test_nm(20, 30, lambda x, y: x * y))
print(test_nm(20, 30, lambda x, y: x + y))
stus = [{"name": "zs", "age": 20}, {"name": "tom", "age": 32}, {"name": "jack", "age": 19}]
通過匿名lambda函數排序,reverse=True 降序。否則為升序
匿名函數作為參數傳遞
stus.sort(key=lambda x: x["age"], reverse=True)
print(stus)
遞歸讀取文件目錄信息
py_list = []
p_dir = r‘E:\2016qBook\2018‘
file_name = r‘PythonCode‘
def read_contain_key_word(parent_dir, file_name, key_word):
full_path = os.path.join(parent_dir, file_name)
if os.path.isdir(full_path):
read_contain_key_word(full_path, f, key_word)
else:
if full_path.endswith(‘.py‘):
if read_key_word(full_path, key_word):
py_list.append(full_path)
def read_key_word(full_path, key_word):
read_flag = False
f = open(full_path, ‘r‘, encoding=‘utf-8‘)
while True:
line = f.readline()
break
elif key_word in line:
read_flag = True
break
f.close()
return read_flag
read_contain_key_word(p_dir, file_name, ‘sort‘)
print(py_list)
Python lambda匿名函數,遞歸應用