目录
一.递归访问目录: 且目录中嵌套目录,有层次的列出给定目录中所有的文件和文件夹
四.对列表进行排序: list_data = ["grape", "peach", "berry", "pineapple", "apple", "strayberry", "watermelon"]
七.利用reduce计算1 + 2 + 3...+ 100之和
一.递归访问目录: 且目录中嵌套目录,有层次的列出给定目录中所有的文件和文件夹
import os
def display_path(path, count=0):
for file_name in os.listdir(path):
sub_path = os.path.join(path, file_name)
if os.path.isdir(sub_path):
print("\t|" * count, file_name)
sub_count = count + 1
display_path(sub_path, sub_count)
if os.path.isfile(sub_path):
print("\t|" * count, file_name)
display_path('E:\\secure')
结果:
二.定义一个嵌套函数,
外层函数打印this is outing function
内层函数功能:打印This is inner function
def outer():
print("this is outing 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)
# 斐波那契数列(Fibonacci sequence),又称黄金分割数列,因数学家
# 莱昂纳多·斐波那契以兔子繁殖为例子而引入,故又称为“兔子数列”,指的是
# 这样一个数列:0、1、1、2、3、5、8、13、21、34、……在数学上,斐波
# 那契数列以如下被以递推的方法定义:
# F(0)=0,F(1)=1, F(n)=F(n - 1)+F(n - 2)(n ≥ 2,n ∈ N*)
def fibonacci_series(arg):
if arg == 0:
return 0
elif arg == 1:
return 1
elif arg >= 2:
return fibonacci_series(arg - 1) + fibonacci_series(arg - 2)
print(fibonacci_series(6))
四.对列表进行排序: list_data = ["grape", "peach", "berry", "pineapple", "apple", "strayberry", "watermelon"]
排序规则:按照最后一个字符进行排序,如果最后一个字符相等,按照第一个字符排序
list_data = ["grape", "peach", "berry", "pineapple",
"apple", "strawberry", "watermelon"]
def fruit_sort(name):
return name[-1], name[0]
list_data.sort(key=lambda name: (name[-1], name[0]))
print(list_data)
结果如下:
五.利用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 = list(map(lambda i, j, k: (i+j+k), list1, list2, list3))
print(sum_list)
六.利用filter函数过滤列表中所有带a的字符串
list_data = ["grape", "what", "which", "you", "friend", "am"]
list_data = ["grape", "what", "which", "you", "friend", "atm"]
filter_data = list(filter(lambda x: 'a' not in x, list_data))
print(filter_data)
七.利用reduce计算1 + 2 + 3...+ 100之和
from functools import reduce
list_data = list(range(1, 101))
sum_data = reduce(lambda x, y: x+y, list_data)
print(sum_data)