python8

Posted songchenguang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python8相关的知识,希望对你有一定的参考价值。

# 1.全局变量,局部变量
# 全局变量:
# 顶头写得。没有任何缩进
# name = ‘lhf‘
#在整个文件中的任何位置都可以调用
# 局部变量:在子程序中可以调用
# name = ‘lhf‘
# def chang_name():
# x = 1#局部变量
# print("chang_name",name)
# chang_name()#chang_name lhf
# 2.
# name = ‘lhf‘
# def chang_name():
# name = ‘帅‘
# x = 1#局部变量
# print("chang_name",name)
# chang_name()#chang_name 帅
# print(name)#lhf
# 3.全局变量
# name = 1
# def chang_name():
# global name
# name = ‘帅‘
# x = 1#局部变量
# print("chang_name",name)
# chang_name()#chang_name 帅
# print(name)#帅
# 4.全局变量
# name = "产品经理"
# def yangjian():
# global name#已经声明,name就是全局变量
# print(‘我是‘,name)
# name = (‘厨师‘)#修改 全局变量
# print(‘卧室‘,name)
# yangjian()
# # 我是 产品经理
# # 卧室 厨师
#如果函数内部没有global关键字,优先读取局部变量,如果局部变量没有,读取全局变量,只能读取,无法重新赋值
#但是对于可变类型,可以对内部元素进行操作
#规范:全局变量都大写,局部变量都小写
# 5.函数的嵌套
# NAME = ‘海风‘
# def huangwei():
# name = ‘huang‘
# print(name)
# def liuyang():
# print(‘liu‘)
# def nulige():
# print(‘hu‘)
# liuyang()
# print(name)
# huangwei()
# huang
#liu
# huang
# NAME = ‘海风‘
# def huangwei():
# name = ‘huang‘
# print(name)
# def liuyang():
# name = "liu"
# print(name)
# def nulige():
# name = ‘hu‘
# print(name)
# print(name)
# nulige()
# liuyang()
# print(name)
# huangwei()
# huang
# liu
# liu
# hu
# huang
# 6.嵌套
# name = "刚娘"
# def weihou():
# name = "陈卓"
# def weiweihou():
# global name
# name = "冷静"
# weiweihou()
# print(name)
# print(name)
# weihou()
# print(name)
# # 刚娘
# # 陈卓
# # 冷静
# 7.#nonlocal#上一级变量
# name = "刚娘"
# def weihou():
# name = "陈卓"
# def weiweihou():
# nonlocal name
# name = "冷静"
# weiweihou()
# print(name)
# print(name)
# weihou()
# print(name)
# 刚娘
# 冷静
# 刚娘
# 8.前项引用
#(1 def foo():
# print(‘from foo‘)
# bar()
# foo()#报错
# (2def bar():
# print(‘from bar‘)
# def foo():
# print(‘from foo‘)
# bar()
# foo()
#from foo
# from bar
# (3
# def foo():
# print(‘from foo‘)
# bar()
# def bar():
# print(‘from bar‘)
# foo()
# from foo
# from bar
# 9.风湿理论,函数即变量
# 10.
# name = ‘海风‘
# def huangwei():
# name = ‘huang‘
# print(name)
# def liuyang():
# name = "liu"
# print(name)
# def nulige():
# name = ‘hu‘
# print(name)
# print(name)
# nulige()
# liuyang()
# print(name)
# print(name)
# huangwei()
# 海风
# huang
# liu
# liu
# hu
# huang
# 11.
# 递归----问路
#在函数中只要碰到return立刻中止
# def calc(n):
# print(n)
# if int(n / 2) == 0:
# return n
# calc(int(n / 2))
# calc(10)
# # 10
# # 5
# # 2
# # 1
# 12.问路
# import time
# person_list = [‘alex‘,‘wupeiqi‘,‘linhaifeng‘,‘zsc‘]
# def ask_way(person_list):
# print(‘_‘*60)
# if len(person_list) == 0:
# return‘根本没人知道‘
# person= person_list.pop(0)
# if person == ‘linhaifeng‘:
# return‘%s说:我知道路在沙河‘ %person
# print(‘hi 美男[%s],路在何方‘ %person)
# print(‘%s回答道,你等我问问%s‘ %(person,person_list))
# time.sleep(1)
# res = ask_way(person_list)
# print(‘%s问的结果:%res‘ %(person,res))
# return res
# res = ask_way(person_list)
# print(res)
# # ____________________________________________________________
# # hi 美男[alex],路在何方
# # alex回答道,你等我问问[‘wupeiqi‘, ‘linhaifeng‘, ‘zsc‘]
# # ____________________________________________________________
# # hi 美男[wupeiqi],路在何方
# # wupeiqi回答道,你等我问问[‘linhaifeng‘, ‘zsc‘]
# # ____________________________________________________________
# # wupeiqi问的结果:‘linhaifeng说:我知道路在沙河‘es
# # alex问的结果:‘linhaifeng说:我知道路在沙河‘es
# # linhaifeng说:我知道路在沙河
# 13.返回函数
# def test1():
# print(‘in the test1‘)
# def test():
# print(‘in the test‘)
# return test1
# res = test()
# print(res())
# in the test
# in the test1
# None
# 14.作用域
# name = ‘alex‘
# def foo():
# name = ‘linhaifeng‘
# def bar():
# print(name)
# return bar
# a = foo()
# print(a)#<function foo.<locals>.bar at 0x05028660> bar的地址
# a()#linhaifeng
# 15.
# 匿名函数 lambda
# def calc(x):
# return x + 1
# res = calc(10)
# print(res)#11
# print(lambda x : x +1)#<function <lambda> at 0x03258660>
# func = lambda x:x+1#前面的x是形参 后面的x+1是要做的运算
# print(func(10))#11
###f = lambda x,y,z:(x+1,y+1,z+1)
# 16.函数式编程
# 不可变数据#不用变量保存状态,不修改变量,在函数体内没有赋值语句
# 函数即变量
# 17.函数即变量
# def foo(n):
# print(n)
# def bar(name):
# print(‘my name is %s‘ %name)
# foo(bar)#<function bar at 0x05248660> bar的地址
# 高阶函数:函数接收的参数是一个函数名,或者返回值中包含函数
# 18.map函数
# num_1 = [1,2,10,5,3,7]
# ret = []
# for i in num_1:
# ret.append(i**2)
# print(ret)
#
# def map_test(array):
# ret = []
# for i in num_1:
# ret.append(i ** 2)
# return ret
# ret = map_test(num_1)
# print(ret)
# # 自加1
# def add_one(x):
# return x-1
# def map_test(func,array):
# ret = []
# for i in num_1:
# res = func(i)
# ret.append(res)
# return ret
# ret = map_test(add_one,num_1)
# print(ret)
#############
# map 方法
# num_1 = [1,2,10,5,3,7]
# res = map(lambda x:x+1,num_1)
# print(res)#<map object at 0x03A4EE30>
# for i in res:
# print(i)
# 2
# 3
# 11
# 6
# 4
# 8
# print(list(res))#[2, 3, 11, 6, 4, 8]
# map 用法:前边方法,后边用可迭代对象,每个元素完成前面的操作。
#函数式编程:map,reduce,filter
# 19.过滤掉看电影爱说话的人
# movie_people = [‘sb_alex‘,‘sb_wupeiqi‘,‘linhaifeng‘,‘sb_yuanhao‘]
# ret = []
# def filer_test(array):
# for p in array:
# if not p.startswith(‘sb‘):
# ret.append(p)
# return ret
# print(filer_test(movie_people))
# ####################
# # filter()用法
# def sb_show(n):
# return n.endswith(‘sb‘)
# movie_people = [‘sb_alex‘,‘sb_wupeiqi‘,‘linhaifeng‘,‘sb_yuanhao‘]
# ret = []
# def filer_test(func,array):
# for p in array:
# if not func(p):
# ret.append(p)
# return ret
# res = filer_test(sb_show,movie_people)
# print(res)
# #终极版本
# lambda n:n.endswith(‘sb‘)
# res = filer_test(lambda n: not n.endswith(‘sb‘),movie_people)
# print(res)
# #filter函数
# res = list(filter(lambda n:not n.endswith(‘sb‘),movie_people))
# print(res)
############
# 20.reduce的用法
# from functools import reduce
# num_1 = [1,2,3,100]
# res = 0
# from num in num_1:
# res += num
# print(res)
# num_l = [1,2,3,100]
# def reduce_test(array):
# res = 0
# for num in array:
# res += num
# return res
# print(reduce_test(num_l))
# 106
# 改写
# num_l = [1,2,3,100]
# def reduce_test(func,array,init=None):
# if init is None:
# res = array.pop(0)
# else:
# res = init
# for num in array:
# res = func(res,num)
# return res
# print(reduce_test(lambda x,y:x*y,num_l,100))
# 21.# #reduce
# from functools import reduce
# num_l = [1,2,3,100]
# res= reduce(lambda x,y:x+y,num_l,1)
# print(res)
########################################
# 总结
# map()
#处理序列中的每个元素,得到的结果是一个‘列表’,该‘列表’元素个数及位置与原来一样#可以处理任何可迭代的序列。
# filter()
# 遍历序列中的每个元素,判断每个元素得到布尔值,如果是True则留下来得到的结果是一个‘列表’
# people=[
# {‘name‘:‘alex‘,‘age‘:1000},
# {‘name‘:‘wupei‘,‘age‘:10000},
# {‘name‘:‘yuanhao‘,‘age‘:9000},
# {‘name‘:‘linhaifeng‘,‘age‘:18},
# ]
# filter(lambda p:p[‘age‘]<=18,people)
# print(list(filter(lambda p:p[‘age‘]<=18,people)))
# # [{‘name‘: ‘linhaifeng‘, ‘age‘: 18}]
# reduce:处理一个序列,然后把序列进行合并操作
# from functools import reduce
# print(reduce(lambda x,y:x+y,range(100),100))
# print(reduce(lambda x,y:x+y,range(1,100)))
# 22.内置函数
# print(abs(-1))
# print(abd(1))
# print(all([1,2,‘1‘]))#True
# print(all([1,2,‘1‘,‘‘]))#False
#如果了迭代对象是空,返回True
# print(all(‘‘))#True
# print(any([1,2,‘‘]))#只要有一个是真就返回真
# 十进制转换成二进制
# print(bin(3))#0b11
# print(bool(‘‘))#False
#手动把字符串转换成编码打印出来
# name = ‘你好‘
# print(bytes(name,encoding=‘utf-8‘))#b‘xe4xbdxa0xe5xa5xbd‘
# decode(‘utf-8‘)解码
# ascii表
# print(chr(564))#?
#dir打印某一个对象下面有哪些方法
# 取商得余数
# print(divmod(10,3))
# (3, 1)
#eval把字符串中的字典提取出来
# 另外一个作用计算用:
# express = ‘1+2*(3/3-1)-2‘
# print(express)#打印出来的是字符串
# print(eval(express))#-1.0 直接计算出结果
# 可hash的数据类型即不可变类型,不可hash的数据类型即可变类型
# hex十进制转成16进制
# oct十进制转成八进制
# print(isinstance(1,int))
# print(isinstance(‘sada‘,int))#False 判断前面的是否是后面的对象
# max取最大值
# l = [1,3,100,-1,2]
# print(max(l))
# print(min(l))
# zip函数 拉链
# print(list(zip((‘a‘,‘b‘,‘c‘),(1,2,3))))#[(‘a‘, 1), (‘b‘, 2), (‘c‘, 3)]
# 例子
# p={‘name‘:‘alex‘,‘age‘:‘18‘,‘gender‘:‘none‘}
# print(list(zip(p.keys(),p.values())))
# [(‘name‘, ‘alex‘), (‘age‘, ‘18‘), (‘gender‘, ‘none‘)]
# max传入的数据类型一定是可迭代类型
# 不同数据类型之间不可比较
# 比较时从第一个开始比较
# 23.
# ord写字符,打印asiic对应的数字
# pow(3,3) 3的3次方
# pow(3,3,2) 3的3次方对2取余
# round四舍五入
# 24.sorted(排序)
# people=[{‘name‘:‘alex‘,‘age‘:1000},
# {‘name‘:‘wupei‘,‘age‘:10000},
# {‘name‘:‘yuanhao‘,‘age‘:9000},
# {‘name‘:‘linhaifeng‘,‘age‘:18}
# ]
# print(sorted(people,key = lambda dic:dic[‘age‘]))#[{‘name‘: ‘linhaifeng‘, ‘age‘: 18}, {‘name‘: ‘alex‘, ‘age‘: 1000}, {‘name‘: ‘yuanhao‘, ‘age‘: 9000}, {‘name‘: ‘wupei‘, ‘age‘: 10000}]
#字典按照年龄排序
# name_dic = {‘y‘:900,‘alex‘:200,‘wupei‘:300}
# print(sorted(name_dic,key=lambda key:name_dic[key]))#[‘alex‘, ‘wupei‘, ‘y‘]#返回结果是key
# print(sorted(zip(name_dic.values(),name_dic.keys())))#取出人名对应的数值和人名 [(200, ‘alex‘), (300, ‘wupei‘), (900, ‘y‘)]
#模块就是一个Py文件
# __import__()#以字符串形式导入模块
########################################
# 25.
# 文件处理
# f = open(‘晨‘,encoding=‘utf8‘)#操作系统编码方式 来借玛
# data = f.read()
# print(data)
# f.close()
#文件打开模式
#r w a
f = open(‘晨‘,‘r‘,encoding=‘utf8‘)#文件只读 f是文件句柄,从操作系统要一个权限
# print(f.readable())#判断文件是否值得读
# print(f.readline())#一次读一行
# print(f.readline(),end=‘‘)#去掉之间的空行
# data = f.readlines()
# print(data)#[‘快乐 (人类精神感受) 编辑 ‘, ‘快乐,汉语词汇,音kuài lè。 ‘,
# 26.
# 写
# f = open(‘晨1‘,‘w‘,encoding=‘utf8‘)
# f.write(‘1111111 ‘)
# f.write(‘22222222222‘)
# f.write(‘333 4566 564454 ‘)
# f.close()
# f.writelines([‘1111 ‘,‘66666 ‘])#以列表的形式写
# #文件的内容全部是字符串
# f.write(3)#baocuo
# 追加 a
# open(‘晨1‘,‘a‘,encoding=‘utf8‘)
# f.write(‘猪八戒‘)
# 27.#可读可写
# f = open(‘xxx‘,‘r+‘,encoding=‘utf-8‘)
# data = f.read()
# print(data)
# f.write(‘1111111111‘)
# 28.#with 不需要close操作
# with open(‘a.txt‘,‘w‘) as f:
# f.write(‘fsfsdg ‘)
# 29.rb用法
#rb的方式不能指定编码
# f = open(‘test11.py‘,‘rb‘)
# data = f.read()
# print(data)#b‘adasd adasfvzxcea awec xe4xbdxa0xe5xa5xbd‘
# 一字节形式打开
# print(data.decode(‘utf-8‘))
#adasd
# adasfvzxcea
# awec
# 你好
# 30.
# 迭代器和生成器
#迭代器协议
# 1.对象必须提供一个next方法,执行该方法要么返回迭代中的下一项,要么就引起一个
# StopIteration异常,以中止迭代(只能往后走,不能往前退)
# 2.可迭代对象:实现了迭代器协议的对象
# 3.(字符串,列表,元祖,字典,集合,文件对象)这些都不是可迭代对象,只不过在for循环时,
# 调用了他们内部的_iter_方法,把他们变成了可迭代对象
# 生成器
# 生成器就是可迭代对象
# def test():
# yield 1
# g = test()
# print(g.__next__())#1
#第二种表达方式
# 三元表达式
# ‘SB‘if name == ‘alex‘ else ‘帅哥‘
#列表解析
# egg_list = []
# for i in range(10):
# egg_list.append(‘鸡蛋%s‘ %i)
# print(egg_list)
# l = [‘鸡蛋%s‘%i for i in range(10) if i > 5]
# print(l)#[‘鸡蛋6‘, ‘鸡蛋7‘, ‘鸡蛋8‘, ‘鸡蛋9‘]
# l = (‘鸡蛋%s‘%i for i in range(10))生成器表达式
# print(l)#<generator object <genexpr> at 0x02F91F70> 生成器
# print(l.__next__())
# print(l.__next__())
# # 鸡蛋0
# # 鸡蛋1
# print(sum(i for i in range(1000)))#生成器表达式
#吃包子
# def product_baozi():
# for i in range(100):
# yield ‘一屉包子%s‘ %i
# pro_g = product_baozi()
# baozil = pro_g.__next__()
# print(‘来了一个人‘,baozil)
# baozi2 = pro_g.__next__()
# print(‘来了一个人‘,baozi2)

 
























































































































































































































































































































































































































































































































以上是关于python8的主要内容,如果未能解决你的问题,请参考以下文章