递归访问目录,嵌套函数,递归函数map函数,filter函数,reduce函数

一、递归访问目录: 且目录中嵌套目录,有层次的列出给定目录中所有的文件和文件夹

def listdir(path, count=0):
    list_dir = os.listdir(path)
    for i in list_dir:
        path1 = os.path.join(path + "/", i)
        if os.path.isdir(path1):
            print(count * "    ", i)
            count1 = count + 1
            listdir(path1, count1)
        else:
            print(count * '    ', i)


listdir('D:test')

# 输出
 1.txt
 2.txt
 test1
     1.txt
     2.txt
     test2
         1.txt

二、定义一个嵌套函数, 外层函数打印this is outing function,内层函数功能:打印This is inner function

def outer():
    print("this is outing function ")

    def inner():
        print("This is inner function")

    return inner


f_inner = outer()
f_inner()

# 输出
this is outing function 
This is inner function

三、定义一个递归函数:

打印斐波那契数列
斐波那契数列指的是这样一个数列 0, 1, 1, 2, 3, 5, 8, 13,特别指出:第0项是0,第1项是第一个1。从第三项开始,每一项都等于前两项之和。

def fib(n):
    if n == 0:
        return [0]
    if n == 1:
        return [0, 1]
    if n == 2:
        return [0, 1, 1]
    fibs = [0, 1, 1]
    for i in range(2, n):
        fibs.append(fibs[-1] + fibs[-2])
    return fibs


print(fib(10))
# 输出
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

四、对列表进行排序:

list_data = [“grape”, “peach”, “berry”, “pineapple”, “apple”, “strayberry”, “watermelon”] 排序规则:按照最后一个字符进行排序,如果最后一个字符相等,按照第一个字符排序

list_data = ["grape", "peach", "berry", "pineapple", "apple", "strayberry", "watermelon"]


def data(x):
    return [-1]


print(list_data)
list_data.sort(key=lambda x: x[-1])
print(list_data)

# 输出
['grape', 'peach', 'berry', 'pineapple', 'apple', 'strayberry', 'watermelon']
['grape', 'pineapple', 'apple', 'peach', 'watermelon', 'berry', 'strayberry']

五、利用map函数: 计算三个列表,相同位置元素之和

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]

六、利用filter函数过滤列表中所有带a的字符串

list_data = ["grape", "what", "which", "you", "friend", "am"]
filter_obj = filter(lambda x: 'a' not in x, list_data)
print(list(filter_obj))
# 输出
5050

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值