目录
7.利用reduce计算1 + 2 + 3...+ 100之和
1.递归访问目录
前导知识:
- 切换目录: os.chdir(path)
- 列出当前目录中所有的文件和文件夹 os.listdir(path), path: 绝对路径
- 判断是否是文件: os.path.isfile(path)
- 判断是否是目录: os.path.isdir(path)
- 拼接路径: os.path.join(path1, path2, path3…)
且目录中嵌套目录,有层次的列出给定目录中所有的文件和文件夹
def show_path(path, count=0):
for filename in os.listdir(path):
# print(filename)
sub_path = os.path.join(path, filename)
if os.path.isdir(sub_path):
print("\t" * count, filename)
sub_count = count + 1
show_path(sub_path, sub_count)
if os.path.isfile(sub_path):
print('\t' * count, filename)
show_path('D:\日常工作\欧鹏学习\Python\资料')
结果如下:
2.定义一个嵌套函数
外层函数打印this is outing function;内层函数功能:打印This is inner function
def outer():
print('this is outing function')
def inner():
print('This is inner function')
inner()
outer()
结果如下:
3.定义一个递归函数:打印斐波那契数列
F[n]=F[n-1]+F[n-2](n>=2,F[0]=0,F[1]=1)
# 3.定义一个递归函数:打印斐波那契数列
# F[n]=F[n-1]+F[n-2](n>=2,F[0]=0,F[1]=1)
# F[0] = 0
# F[1] = 1
# F[2] = F[1] + F[0] = 1 + 0 = 1
# F[3] = F[2] + F[1] = 1 + 1 = 2
# F[4] = F[3] + F[2] = 2 + 1 = 3
# F[5] = f[4] + F[3] = 3 + 2 = 5
def fibonacci_seq(arg):
if arg == 0:
return 0
if arg == 1:
return 1
if arg >= 2:
return fibonacci_seq(arg-1) + fibonacci_seq(arg-2)
print(fibonacci_seq(5)) # 5
4.对列表进行排序:
list_data = ["grape", "peach", "berry", "pineapple", "apple", "strayberry", "watermelon"]
排序规则:按照最后一个字符进行排序,如果最后一个字符相等,按照第一个字符排序
list_data = ["grape", "peach", "berry", "pineapple", "apple", "strayberry", "watermelon"]
def sort_role(x):
return x[-1], x[0]
# list_data.sort(key=sort_role)
list_data.sort(key=lambda x: (x[-1], x[0]))
print(list_data)
结果:['apple', 'grape', 'pineapple', 'peach', 'watermelon', 'berry', 'strayberry']
5.利用map函数: 计算三个列表,相同位置元素之和
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = [7, 8, 9]
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(sum_list) # 返回的是一个map对象
print(list(sum_list))
# 结果:[12, 15, 18]
6.利用filter函数过滤列表中所有带a的字符串
list_data = ["grape", "what", "which", "you", "friend", "am"]
list_data = ["grape", "what", "which", "you", "friend", "am"]
result = filter(lambda x: 'a' not in x, list_data)
# print(result) # 返回一个filter类型的对象
print(list(result))
# 结果:['which', 'you', 'friend']
7.利用reduce计算1 + 2 + 3...+ 100之和
from functools import reduce
list_data = list(range(1, 101))
# print(list_data)
result = reduce(lambda x, y: x+y, list_data)
print(result) # 结果:5050