import os
‘‘‘
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):
for f in os.listdir(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()
if line == "":
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)
原文地址:http://blog.51cto.com/6000734/2313270