文章目录
前言
学习python
一、递归访问目录: 且目录中嵌套目录,有层次的列出给定目录中所有的文件和文件夹
代码
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("D:\study\python_code\ext")
print(os.getcwd())
运行
二、定义一个嵌套函数
外层函数打印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()
运行
三、定义一个递归函数:打印斐波那契数列
代码
F[n]=F[n-1]+F[n-2](n>=2,F[0]=0,F[1]=1)
def f_func(n):
if n == 1:
return 0
if n == 2:
return 1
if n > 2:
return f_func(n - 1) + f_func(n - 2)
list_data = []
for i in range(1, 10):
data = f_func(i)
list_data.append(data)
print(list_data)
运行
四、对列表进行排序: list_data = [“grape”, “peach”, “berry”, “pineapple”, “apple”, “strayberry”, “watermelon”]
排序规则:按照最后一个字符进行排序,如果最后一个字符相等,按照第一个字符排序
代码
list_data = ["grape", "peach", "berry", "pineapple", "apple", "strayberry", "watermelon"]
list_data.sort(key=lambda n: (n[-1], n[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 = map(lambda x, y, z: x + y + z, list1, list2, list3)
print(list(sum))
运行
六、利用filter函数过滤列表中所有带a的字符串
“grape”, “what”, “which”, “you”, “friend”, “am”
代码
list_data = ["grape", "what", "which", "you", "friend", "am"]
print(list(filter(lambda x: "a" in x, list_data)))
运行
七、利用reduce计算1 + 2 + 3…+ 100之和
代码
from functools import reduce
list_data1 = list(range(1, 101))
sum1 = reduce(lambda x, y: x+y, list_data1)
print(sum1)
运行
总结
学习python