我是靠谱客的博主 霸气溪流,这篇文章主要介绍Python 递归访问目录;定义一个嵌套函数;递归函数打印斐波那契数列;map函数;filter函数过滤;reduce求和一、递归访问目录二、定义一个嵌套函数三、定义一个递归函数:打印斐波那契数列四、对列表进行排序五、计算三个列表,相同位置元素之和六、利用filter函数过滤列表中所有带a的字符串七、利用reduce计算1 + 2 + 3…+ 100之和,现在分享给大家,希望可以做个参考。

一、递归访问目录

要求:且目录中嵌套目录,有层次的列出给定目录中所有的文件和文件夹
提示:要用到os模块

  • 切换目录: os.chdir(path)
  • 列出当前目录中所有的文件和文件夹 os.listdir(path), path: 绝对路径
  • 判断是否是文件: os.path.isfile(path)
  • 判断是否是目录: os.path.isdir(path)
  • 拼接路径: os.path.join(path1, path2, path3…)
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import os def list_dir_content(dir_path, count=0): for file_name in os.listdir(dir_path): 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) if os.path.isfile(sub_path): print(count * "t" + file_name) list_dir_content("E:Pythonpython_code")

运行结果:
在这里插入图片描述


二、定义一个嵌套函数

要求: 外层函数打印this is outing function;内层函数功能:打印This is inner function

复制代码
1
2
3
4
5
6
7
8
def outer(): print("This is outer function") def inner(): print("This is inner function") inner() outer()

运行结果:
在这里插入图片描述


三、定义一个递归函数:打印斐波那契数列

提示: F[n]=F[n-1]+F[n-2] (n>=2,F[0]=0,F[1]=1)

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def func(a): def func_1(n): if n == 0: return 0 elif n == 1 or n == 2: return 1 else: return func_1(n-2) + func_1(n-1) list_1 = [] for i in range(a): list_1.append(func_1(i)) return list_1 print(func(10))

运行结果:
在这里插入图片描述


四、对列表进行排序

要求:
对列表进行排序: list_data = [“grape”, “peach”, “berry”, “pineapple”, “apple”, “strayberry”, “watermelon”]
排序规则:按照最后一个字符进行排序,如果最后一个字符相等,按照第一个字符排序

复制代码
1
2
3
4
5
6
7
8
list_data = ["grape", "peach", "berry", "pineapple", "apple", "strawberry", "watermelon"] # list_data.sort() # print(list_data) data = lambda x: ([-1], [0]) list_data.sort(key=data) print(list_data)

运行结果:
在这里插入图片描述


五、计算三个列表,相同位置元素之和

要求:
1.利用map函数
2.列表:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = [7, 8, 9]

复制代码
1
2
3
4
5
6
list1 = [1, 2, 3] list2 = [4, 5, 6] list3 = [7, 8, 9] sum_list = map(lambda x, y, z: (x+y+z), list1, list2, list3) print(list(sum_list))

运行结果:
在这里插入图片描述


六、利用filter函数过滤列表中所有带a的字符串

列表:list_data = [“grape”, “what”, “which”, “you”, “friend”, “am”]

复制代码
1
2
3
4
list_data = ["grape", "what", "which", "you", "friend", "am"] result = filter(lambda x: "a" not in x, list_data) print(list(result))

运行结果:
在这里插入图片描述

七、利用reduce计算1 + 2 + 3…+ 100之和

复制代码
1
2
3
4
list_data = ["grape", "what", "which", "you", "friend", "am"] result = filter(lambda x: "a" not in x, list_data) print(list(result))

运行结果:
在这里插入图片描述

最后

以上就是霸气溪流最近收集整理的关于Python 递归访问目录;定义一个嵌套函数;递归函数打印斐波那契数列;map函数;filter函数过滤;reduce求和一、递归访问目录二、定义一个嵌套函数三、定义一个递归函数:打印斐波那契数列四、对列表进行排序五、计算三个列表,相同位置元素之和六、利用filter函数过滤列表中所有带a的字符串七、利用reduce计算1 + 2 + 3…+ 100之和的全部内容,更多相关Python内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(65)

评论列表共有 0 条评论

立即
投稿
返回
顶部