B站 【小甲鱼】零基础入门学习python 笔记 - 3

原视频链接:https://search.bilibili.com/all?keyword=BV1xs411Q799&from_source=nav_search_new

020 函数:内嵌函数和闭包
count = 5

def Function():
    global count
    count = 10
    print(count)

Function()
# 10
print(count)
# 10 count设置为全局变量,但是在函数中加入了global count这个语句,使得函数中原本的局部变量变成了全局变量。

def func1():
    print('I love Hello')
    def func2():
        print('I love World')
    func2()

func1()
# I love Hello
# I love World func2()就是所谓的内嵌函数

def FunX(x):
    def FunY(y):
        return x * y
    return FunY
i = FunX(8)
print(i(5))
# 40 i = FunX(8)-> x = 8; i(5) -> y = 5; 5 * 8 = 40

def Fun1():
    x = 5
    def Fun2():
        x *= x
        return x
    return Fun2()
print(Fun1())
# 这样是会直接报错的,因为Fun2嵌入在Fun1中,是无权改变Fun1中所设的‘全局变量的’
# 但是,如果在x*=x前加个nonlocal x(和global x效果一样)或者将x变成一个列表,就可以防止错误的发生
021 函数:lambda表达式

lambda可以省下定义函数和给函数取名字的问题,简化代码的可读性

def ds(x):
    return 2 * x + 1
ds(5)
# 11

g = lambda x : x * 2 + 1
print(g(5))
# 11 g称作匿名函数

g1 = lambda x, y : x + y + 1
print(g1(4,5))
# 10 两个参数

print(list(filter(None, [1, 0, False, True])))
# [1, True] filter()第一个参数为None,那就是自动讲后面参数中为‘真’的元素筛选出来
def odd(x):
    return x % 2
temp = range(10)
show = filter(odd, temp)
print(list(show))
# [1, 3, 5, 7, 9] filter()的第一个参数若为函数,那就是按照自己定的方式来筛选数据

print(list(filter(lambda x : x % 2, range(10))))
# [1, 3, 5, 7, 9] 一样的效果,更简单的语句

print(list(map(lambda x : x * 2, range(10))))
# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] map是映射的意思,map()是将第二个可迭代的参数(全部)放到第一个函数中运行,然后得出结果
022 函数:递归是神马
def Mult(x):
    sum = 1
    for i in range(x):
        sum = sum * (i+1)
    print(sum)
Mult(4) # 24 递归求阶层 1.0 (非递归版本)

def Mult1(n):
    if n == 1:
        return 1
    else:
        return n * Mult1(n-1)
print(Mult1(5)) # 120 递归求阶层 2.0 (递归版本

023 递归:这帮小兔崽子

斐波那契数列:兔子繁殖问题

def Fi1(x):
    n1 = 1
    n2 = 1
    n3 = 2

    if(x < 1):
        print('Wrong!')

    while(x > 2):
        n3 = n1 + n2
        n1 = n2
        n2 = n3
        x = x - 1
    return n3
print(Fi1(20))
# 非递归方式,计算斐波那契数列第x位的值

def Fi(x):
    if x == 1 or x == 2:
        return 1
    else:
        return Fi(x - 1) + Fi(x - 2)
print(Fi(20))
# 6765 递归方式,计算斐波那契数列第x位的值

递归方法有时候会造成运算效率的降低,谨慎使用

024 递归:汉诺塔
def hanoi(n, x, y, z):
    if n == 1:
        print(x, '-->', z)
    else:
        hanoi(n-1, x, z, y) # 将前n-1个盘子从x移动到y上
        print(x, '-->', z) # 将最底下的最后一个盘子从x移动到z上
        hanoi(n-1, y, x, z) # 将y上的n-1个盘子移动到z上

n = int(input('请输入汉诺塔的层数:'))
hanoi(n, 'X', 'Y', 'Z')
025 字典:当索引不好用时 1
brand = ['Nike', '李宁', 'Adidas', '鱼C']
slogan = ['Just do it', 'Evething is possible', 'Impossible is nothing', '让编程改变世界']
print('Nike\'s slogan is: ', slogan[brand.index('Nike')])
# Nike's slogan is:  Just do it 非字典方法将两个列表关联起来

dict1 = {'Nike': 'Just do it', '李宁': 'Evething is possible', 'Adidas': 'Impossible is nothing', '鱼C':'让编程改变世界'}
print('Adidas\'s slogan is: ', dict1['Adidas'])
# Adidas's slogan is:  Impossible is nothing 用字典方式映射答案

dict2 = dict((('F', 70), ('i', 105), ('s', 115), ('h', 104), ('C', 67)))
print((dict2))
# {'F': 70, 'i': 105, 's': 115, 'h': 104, 'C': 67} 形成字典,例子中使用的是元组,也可以用列表

dict3 = dict(小甲鱼 = 'qwer', 大甲鱼 = 'asdf')
print(dict3)
# {'小甲鱼': 'qwer', '大甲鱼': 'asdf'}

dict3['大甲鱼'] = 'QWER'
print(dict3)
# {'小甲鱼': 'qwer', '大甲鱼': 'QWER'} 改变dict3中的值

dict3['甲鱼'] = 'IOPU'
print(dict3)
# {'小甲鱼': 'qwer', '大甲鱼': 'QWER', '甲鱼': 'IOPU'} 添加
026 字典:当索引不好用时 2
dict1 = {}
print(dict1.fromkeys((1, 2, 3)))
# {1: None, 2: None, 3: None} 可用来初始化字典
print(dict1.fromkeys((1, 2, 3), 'Number'))
# {1: 'Number', 2: 'Number', 3: 'Number'}
print(dict1.fromkeys((1, 2, 3), ('Number', 'two', 'three')))
# {1: ('Number', 'two', 'three'), 2: ('Number', 'two', 'three'), 3: ('Number', 'two', 'three')}

dict1 = dict1.fromkeys(range(16), '赞')
print(dict1)
# {0: '赞', 1: '赞', 2: '赞', 3: '赞', 4: '赞', 5: '赞', 6: '赞', 7: '赞', 8: '赞', 9: '赞', 10: '赞', 11: '赞', 12: '赞', 13: '赞', 14: '赞', 15: '赞'}

for eachKey in dict1.keys():
    print(eachKey)
# 0 1 ..... 15 将字典的索引打出来了

for eachValue in dict1.values():
    print(eachValue)
# 赞 。。。。 赞 打印出全部值

for eachitems in dict1.items():
    print(eachitems)
# (0, '赞') ... (15, '赞') 将整个字典打印出来

print(dict1.get(15))  # 赞
print(dict1.get(16))  # None
print(15 in dict1)  # True
print(16 in dict1)  # False

dict1.clear()
print(dict1)
# {} clear清空字典

b = {'as', 'AS'}
a = b
a.clear()
# clear a 时,a = b = {}

b = {'as', 'AS'}
a = b.copy()
c = b
print(id(a))  # 15266056
print(id(b))  # 15265944
print(id(c))  # 15265944
# 其实和之前列表里[:]类似,从地址中也可以更直观的看出,用copy()方法,a有了新的地址,而直接赋值的话,c和b还是共用一个地址的(即b变c一起变)

dict2 = {1: 'one', 2: 'two', 3: 'three'}
print(dict2.pop(2))  # two
print(dict2)  # {1: 'one', 3: 'three'}
# 跟列表里的pop功能一样

print(dict2.popitem())  # (3, 'three')
print(dict2)  # {1: 'one'}
# 将整个item pop出去,但是字典中是不讲究顺序的,所以是随机pop并删除一对key+value

dict2 = {1: 'one', 2: 'two', 3: 'three'}
dict3 = {4: 'four'}
dict2.update(dict3)
print(dict2)
# {1: 'one', 2: 'two', 3: 'three', 4: 'four'} 将dict2和dict3结合
027 集合:在我的世界里,你就是唯一
dict = {1, 2, 3, 4, 5, 6}
print(type(dict))
# <class 'set'> 花括号不是字典的专属,如果都是这样的形式,那就是集合

num = {1, 2, 3, 4, 5, 3, 2, 1, 5, 2, 1}
print(num)
# {1, 2, 3, 4, 5} 集合里的元素是唯一的,若重复会自动剔除
# 但是,集合是无序的,我们不可以用索引来定向查找集合里的某个数

set1 = set([1, 2, 3, 4, 5, 6, 3, 2, 1])
print(set1)
# {1, 2, 3, 4, 5, 6} 第二种创建集合的方法,用set();当然()里除了可以放list之外,也可以放元组

print(list(set1))
# [1, 2, 3, 4, 5, 6] 集合转化为列表,但是在列表->集合->列表的操作中,会改变列表一开始的顺序,谨慎使用

set1.add(7)
set1.remove(5)
print(set1)
# {1, 2, 3, 4, 6, 7} 去掉5,增加7

num3 = frozenset([2, 3, 4, 5, 6])
print(num3)
# frozenset({2, 3, 4, 5, 6}) 创建不可变集合

028 文件:因为懂你,所以永恒

help(open) : 在这里插入图片描述
在这里插入图片描述

# print(help(open))

f = open('F:\\Game.txt', 'r')
#  取得文件对象

print(f.read())
# 读取完文件内容 ()内可加入具体想要读取多少字符

f.close()
f = open('F:\\Game.txt', 'r')
f.read(5)
print(f.tell())
# 6 tell()返回当前文件指针的位置,因为read了前5个字符,所以当前指针指在第六位

f.seek(10, 0)
print(f.tell())
# 10 seek()起到移动指针的作用,‘0’代表从头开始,还有‘1’和‘2’两种选择

f.seek(0, 0)
print(list(f))
# ['Hi !\n', 'Hello World !\n', 'How are you ?\n'] 从指针位置开始,把后面的内容转化为list

f.seek(0, 0)
for each_line in f:
    print(each_line)
# print出文件内容

f.close()
f = f = open('F:\\Game.txt', 'w')
f.write("I love you!")
f.close()
# 文件中写入了‘I love you’,但是之前的内容被覆盖了
029 文件:一个任务

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值