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

list_data = ["grape", "what", "which", "you", "friend", "am"]
print(list(filter(lambda x: "a" in x, list_data)))
['grape', 'what', '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)])
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值