递归访问目录,嵌套函数,递归函数map函数,filter函数,reduce函数
一、递归访问目录: 且目录中嵌套目录,有层次的列出给定目录中所有的文件和文件夹
def listdir(path, count=0):
list_dir = os.listdir(path)
for i in list_dir:
path1 = os.path.join(path + "/", i)
if os.path.isdir(path1):
print(count * " ", i)
count1 = count + 1
listdir(path1, count1)
else:
print(count * ' ', i)
listdir('D:test')
# 输出
1.txt
2.txt
test1
1.txt
2.txt
test2
1.txt
二、定义一个嵌套函数, 外层函数打印this is outing function,内层函数功能:打印This is inner function
def outer():
print("this is outing function ")
def inner():
print("This is inner function")
return inner
f_inner = outer()
f_inner()
# 输出
this is outing function
This is inner function
三、定义一个递归函数:
打印斐波那契数列
斐波那契数列指的是这样一个数列 0, 1, 1, 2, 3, 5, 8, 13,特别指出:第0项是0,第1项是第一个1。从第三项开始,每一项都等于前两项之和。
def fib(n):
if n == 0:
return [0]
if n == 1:
return [0, 1]
if n == 2:
return [0, 1, 1]
fibs = [0, 1, 1]
for i in range(2, n):
fibs.append(fibs[-1] + fibs[-2])
return fibs
print(fib(10))
# 输出
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
四、对列表进行排序:
list_data = [“grape”, “peach”, “berry”, “pineapple”, “apple”, “strayberry”, “watermelon”] 排序规则:按照最后一个字符进行排序,如果最后一个字符相等,按照第一个字符排序
list_data = ["grape", "peach", "berry", "pineapple", "apple", "strayberry", "watermelon"]
def data(x):
return [-1]
print(list_data)
list_data.sort(key=lambda x: x[-1])
print(list_data)
# 输出
['grape', 'peach', 'berry', 'pineapple', 'apple', 'strayberry', 'watermelon']
['grape', 'pineapple', 'apple', 'peach', 'watermelon', 'berry', 'strayberry']
五、利用map函数: 计算三个列表,相同位置元素之和
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = [7, 8, 9]
map_obj = map(lambda x, y, z: x + y + z, list1, list2, list3)
print(list(map_obj))
# 输出
[12, 15, 18]
六、利用filter函数过滤列表中所有带a的字符串
list_data = ["grape", "what", "which", "you", "friend", "am"]
filter_obj = filter(lambda x: 'a' not in x, list_data)
print(list(filter_obj))
# 输出
5050