Python---day7作业

Python---day7作业,第1张

Python---day7作业

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("E:KwDownload")
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("E:KwDownload")
.
E:KwDownload
['Lyric', 'My Lrcx', 'song', 'Temp']
--Lyric
--My Lrcx
--song
--Temp
----7505624AD75ED4F3.zip

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”]

7.利用reduce计算1 + 2 + 3…+ 100之和

n1=1;n2=100
print reduce(lambda x,y:x+y,[i for i in xrange(n1,n2+1)])

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5073783.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-11-16
下一篇2022-11-16

发表评论

登录后才能评论

评论列表(0条)

    保存