一、递归访问目录: 且目录中嵌套目录,有层次的列出给定目录中所有的文件和文件夹
def list_dir_content(dir_path, count=0):
for file_name in os.listdir(dir_path):
# print(file_name)
sub_path = os.path.join(dir_path, file_name)
if os.path.isdir(sub_path):
print('|' + count * '\t' + file_name)
sub_count = count + 1
list_dir_content(sub_path, sub_count)
elif os.path.isfile(sub_path):
print(count * '\t' + file_name)
list_dir_content('D:\\test')
结果:
|test1
| test2
| test3
| test4
进程已结束,退出代码0
二、定义一个嵌套函数
外层函数打印this is outing function
内层函数功能:打印This is inner function
def outer_func():
print('this is outing function')
def inner_func():
print('This is inner function')
return inner_func
inner_f = outer_func()
inner_f()
结果:
this is outing function
This is inner function
进程已结束,退出代码0
三、定义一个递归函数:打印斐波那契数列
F[n]=F[n-1]+F[n-2](n>=2,F[0]=0,F[1]=1)
def func_three(n, arg1=0, arg2=1):
while n > 0:
i = arg1
print(i, end=' ')
arg1, arg2 = arg2, arg1 + arg2
# 这种赋值,先计算等值 右边 就是 arg2=1 arg1+arg2=1
# 再赋值给arg1和arg2,那么 arg1=1, arg2=1
# 如果是arg1 = arg2, arg2 = arg1 + arg2
# 此时 arg2=1, 那么arg1=1,那么 arg2 = 2
n -= 1
return func_three(n, arg1, arg2)
func_three(20)
结果:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181
四、对列表进行排序
list_data = [“grape”, “peach”, “berry”, “pineapple”, “apple”, “strayberry”, “watermelon”]
排序规则:按照最后一个字符进行排序,如果最后一个字符相等,按照第一个字符排序
func_three(20)
list_data = ["grape", "peach", "berry", "pineapple", "apple", "strawberry", "watermelon"]
list_data.sort(key=lambda y: (y[-1], y[0]))
print(list_data)
结果:
['apple', 'grape', 'pineapple', 'peach', 'watermelon', 'berry', 'strawberry']
五、利用map函数: 计算三个列表,相同位置元素之和
list1 = [0, 1, 2]
list2 = [3, 4, 5]
list3 = [6, 7, 8]
map_obj = map(lambda x, y, z: x + y + z, list1, list2, list3)
print(list(map_obj))
结果:
[9, 12, 15]
六、利用filter函数过滤列表中所有带a的字符串
list_data = ["grape", "what", "which", "key", "friend", "you", "love", "wr"]
filter_obj = filter(lambda x: 'a' not in x, list_data)
print(list(filter_obj))
结果:
['which', 'key', 'friend', 'you', 'love', 'wr']
七、利用reduce计算1 + 2 + 3…+ 100之和
from functools import reduce
reduce_obj = reduce(lambda x, y: x + y, range(1,101 ))
print(reduce_obj)
结果:
5050