【无标题】


前言

学习python

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

代码

import os


def list_dir_content(dir_path, count=0):
    for file_name in os.listdir(dir_path):
        sub_path = os.path.join(dir_path, file_name)
        if os.path.isdir(sub_path):
            print(count * "\t" + file_name)
            sub_count = count + 1
            list_dir_content(sub_path, sub_count)
        if os.path.isfile(sub_path):
            print(count * "\t" + file_name)



list_dir_content("D:\study\python_code\ext")
print(os.getcwd())

运行

在这里插入图片描述

二、定义一个嵌套函数

外层函数打印this is outing function
内层函数功能:打印This is inner function

代码

def outer():
    print('this is outing function')
    def inner():
        print('This is inner function')
    return inner()
outer()

运行

在这里插入图片描述

三、定义一个递归函数:打印斐波那契数列

代码

F[n]=F[n-1]+F[n-2](n>=2,F[0]=0,F[1]=1)
def f_func(n):
    if n == 1:
        return 0
    if n == 2:
        return 1
    if n > 2:
        return f_func(n - 1) + f_func(n - 2)


list_data = []
for i in range(1, 10):
    data = f_func(i)
    list_data.append(data)
print(list_data)

运行

在这里插入图片描述

四、对列表进行排序: list_data = [“grape”, “peach”, “berry”, “pineapple”, “apple”, “strayberry”, “watermelon”]

排序规则:按照最后一个字符进行排序,如果最后一个字符相等,按照第一个字符排序

代码

list_data = ["grape", "peach", "berry", "pineapple", "apple", "strayberry", "watermelon"]
list_data.sort(key=lambda n: (n[-1], n[0]))
print(list_data)

运行

在这里插入图片描述

五、利用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]
sum = map(lambda x, y, z: x + y + z, list1, list2, list3)
print(list(sum))

运行

在这里插入图片描述

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

“grape”, “what”, “which”, “you”, “friend”, “am”

代码

list_data = ["grape", "what", "which", "you", "friend", "am"]
print(list(filter(lambda x: "a" in x, list_data)))

运行

在这里插入图片描述

七、利用reduce计算1 + 2 + 3…+ 100之和

代码

from functools import reduce
list_data1 = list(range(1, 101))
sum1 = reduce(lambda x, y: x+y, list_data1)
print(sum1)

运行

在这里插入图片描述

总结

学习python

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值