栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python---day7作业

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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)])
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/423672.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号