递归思想在python中的体现,斐波那契数列,迭代器(map()),过滤器(filter()),高级函数,嵌套函数。用reduce()函数计算1-100之和

目录

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

二.定义一个嵌套函数.

三.定义一个递归函数:打印菲波那契数列F(n)=F(n-1)+F(n-2)(n>=2,F(0)=0,F(1)=1).

四.对列表进行排序.

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

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

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


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

在这里我们先在D盘新建一个目录test,test目录中包含一个test1文件夹和test.txt文件,test1文件夹中包含test2和test.xsl,test2文件夹中包含test3和test.doc,test2文件夹中包含test3.txt.

对于文件夹的操作,我们需要使用到os模块.

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:\\test")
print(os.getcwd())

#执行结果
test.txt.txt
test1
	test.xls.xls
	test2
		test.doc.doc
		test3
			test3.txt.txt
D:\Python\python_code

进程已结束,退出代码0

二.定义一个嵌套函数.

要求:外层函数打印this is outing function,内层函数打印This is inner function

def outing():
    print('this is outing fuction')
    def inner():
        print('this is inner fuction')
    inner()
outing()

#执行结果
this is outing fuction
this is inner fuction

进程已结束,退出代码0

三.定义一个递归函数:打印菲波那契数列F(n)=F(n-1)+F(n-2)(n>=2,F(0)=0,F(1)=1).

def Fibonacci_series(n):
    a = [0]
    if n > 1:
        a = [0, 1]
        for i in range(n-2):
            a.append(a[-2] + a[-1])
    return a
print(Fibonacci_series(10))

#执行结果
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

进程已结束,退出代码0

四.对列表进行排序.

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

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

def get_three_char(str_data):
    return str_data[-1], str_data[0]      #按照最后一个字母排序,若相同比较倒数第一个
list_data =  ['grape','peach','berry','pineapple','apple','strayberry','watermelon']
list_data.sort(key=get_three_char)
print(list_data)

#执行结果
['apple', 'grape', 'pineapple', 'peach', 'watermelon', 'berry', 'strayberry']

进程已结束,退出代码0

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

list1 = [1, 2, 3]

list2 = [4, 5, 6]

list3 = [7, 8, 9]

·  map(func, *iterables) --> map object

参数:

func: 函数

*iterable: 多个可迭代对象

返回值:返回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]

进程已结束,退出代码0

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

list_data = ['grape','what','which','you','friend','am']

·  filter(function or None, iterable) --> filter object

参数:

function or None: 函数或空

iterable: 一个可迭代对象

返回值: filter object: 一个filter类型的对象

功能: 过滤器

有function的情况,将iterable中的每一个元素传递function,

    返回值为True保留,为False的过滤掉

没有function的情况, 将iterable中元素,类似于执行bool(item)

    如果是True保留,False过滤

返回的是一个迭代器,产生的元素是来自iterable中元素作为参数传递给function

拿到值是True情况。 如果没有function的情况,返回元素本身为True的元素

Return an iterator yielding those items of iterable for which function(item)

is true. If function is None, return the items that are true.

在这里由于函数比较简单,我们直接使用lambda表达式解决函数问题.

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

#执行结果
['which', 'you', 'friend']

进程已结束,退出代码0

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

·  reduce: 之前也是放在builtins.py中的,只是后来做了迁移

reduce(function, sequence[, initial]) -> value

# 可以有两个参数,也可以有三个参数

function: 函数

sequence: 序列

initial: 初始化

reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])

((((1+2)+3)+4)+5)

第一次lambda中的x, y 列表中的1, 2

第二次lambda中的x, y 是 x=是第一次labmbda的结果, y=3

......

n!= n * n-1 * n-2....3 * 2 * 1

1..100 = 1 + 2 + 3 +...100

在这我们仍然使用lambda表达式解决定义一个函数的问题.

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

#执行结果
5050

进程已结束,退出代码0

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

shadow_58

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值