@[T]
1.递归访问目录: 且目录中嵌套目录,有层次的列出给定目录中所有的文件和文件夹
#切换目录: os.chdir(path)
#列出当前目录中所有的文件和文件夹 os.listdir(path), path: 绝对路径
#判断是否是文件: os.path.isfile(path)
#判断是否是目录: os.path.isdir(path)
#拼接路径: os.path.join(path1, path2, path3…)
import os
os.chdir("D:\study")
print(os.curdir)
print(os.path.abspath(os.curdir))
print(os.listdir(os.curdir))
def list_all_files(path, sep_count=1):
for sub_path in os.listdir(path):
if os.path.isfile(os.path.join(path, sub_path)):
print("--" * sep_count, sub_path, sep="")
if os.path.isdir(os.path.join(path, sub_path)):
print("--" * sep_count, sub_path, sep="")
list_all_files(os.path.join(path, sub_path), sep_count=sep_count + 1)
list_all_files("D:\study")
# 输出结果为:
D:\study
['ISO', 'Python', 'VMware', 'Xftp', 'Xshell']
--ISO
----rhel-8.5-x86_64-dvd.iso
--Python
----Pycharm
------.idea
--------.gitignore
--------inspectionProfiles
----------profiles_settings.xml
--------misc.xml
--------modules.xml
--------Pycharm.iml
--------workspace.xml
------Pycharm_Professional_2021.2.1_Protable
--------Pycharm_Professional_2021.2.1_Protable
----------.DS_Store
----------bin
2.定义一个嵌套函数
外层函数打印this is outing function
内层函数功能:打印This is inner function
def outer():
def inner():
print("this is outing function")
print("This is inner function")
inner()
outer()
# 输出结果为:
This is inner function
this is outing function
3.定义一个递归函数:打印斐波那契数列
F[n]=F[n-1]+Fn-2
def feibo_func(n):
if n == 1:
return 0
if n == 2:
return 1
if n > 2:
return feibo_func(n - 1) + feibo_func(n - 2)
list_data = []
for i in range(1, 20):
data = feibo_func(i)
list_data.append(data)
print(list_data)
# 输出结果为:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584]
4.对列表进行排序: list_data = [“grape”, “peach”, “berry”, “pineapple”, “apple”, “strayberry”, “watermelon”]
排序规则:按照最后一个字符进行排序,如果最后一个字符相等,按照第一个字符排序
list_data = ["grape", "peach", "berry", "pineapple", "apple", "strayberry", "watermelon"]
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]
map_obj = map(lambda x, y, z: x + y + z, list1, list2, list3) #产生一个新的迭代器
print(list(map_obj))
# 输出结果为:
[12, 15, 18]
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)))
# 输出结果为:
['which', 'you', 'friend']
7.利用reduce计算1 + 2 + 3…+ 100之和
print(reduce(lambda x, y: x + y, range(1, 101)))
# 输出结果为:
5050