文章目录
1.递归访问目录: 且目录中嵌套目录,有层次的列出给定目录中所有的文件和文件夹
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('E:text1')
2.定义一个嵌套函数,外层函数打印this is outing function,内层函数功能:打印This is inner function
def outer():
print('this is outing function')
def inner():
print('this is inner function')
return inner
outer()()
3.定义一个递归函数:打印斐波那契数列
F[n]=F[n-1]+F[n-2] (n>=2,F[0]=0,F[1]=1)
'''
1 1 2 3 5 8 13
1 2 3 4 5 6 7
f(7) = f(6) + f(5)
f(n) = f(n-1) + f(n-2)
'''
def print_info(n):
if n == 1 or n == 2:
return 1
else:
return print_info(n - 1) + print_info(n - 2)
sum1 = print_info(7)
print(sum1)
4.对列表进行排序:
list_data = [“grape”, “peach”, “berry”, “pineapple”, “apple”, “strayberry”, “watermelon”]
排序规则:按照最后一个字符进行排序,如果最后一个字符相等,按照第一个字符排序
def sort(string):
return string[-1], string[0]
list_data = ["grape", "peach", "berry", "pineapple", "apple", "strawberry", "watermelon"]
list_data1 = sorted(list_data, key=sort)
print(list_data1)
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]
print(list(map(lambda x, y, z: x + y + z, list1, list2, list3)))
6.利用filter函数过滤列表中所有带a的字符串
list_data = [“grape”, “what”, “which”, “you”, “friend”, “am”]
list_data = ["grape", "what", "which", "you", "friend", "am"]
print(list(filter(lambda x: 'a' not in x, list_data)))
7.利用reduce计算1 + 2 + 3…+ 100之和
print(reduce(lambda x, y: x + y, range(1, 101)))